-1

I have a txt that is something like this:

Jhon 113
Paul 024
David 094
Peter 085

and from each line i want to have 2 variables one of the type string for the name and one int for the number

I wrote this code and what it does its take what ever a line says and ands it to an array called names but i will like to khow how to split the line into two different variables.

import java.io.*;
public class Read {
    public static void main(String[] args) throws Exception{

        FileReader file = new FileReader("test.txt");
        BufferedReader reader = new BufferedReader(file);
        String names[] = new String[10];
        for(int i = 0; i<names.length;  i++){
            String line = reader.readLine();
            if(line != null){
                names[i] = line;
            }
        }               
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Juan Alvarez
  • 29
  • 1
  • 6
  • 1
    You didn't write this code. If you did, you would know how to split those two values. – f1sh Oct 22 '15 at 18:01
  • `String.split("\\s+");` returns a `String[]` of each`String` split at `space` – 3kings Oct 22 '15 at 18:02
  • i actually did write that code but i tested it with only the name and i dident khow how to split them and that code you put there does not returns an int and a string it returns and array of strings – Juan Alvarez Oct 22 '15 at 18:05

2 Answers2

0

You should use split() :

String names[] = new String[10];
int numbr[] = new int[10];
    for(int i = 0; i<names.length;  i++){
        String line = reader.readLine();
        if(line != null){
            names[i] = line.split(" ")[0];
            numbr[i] = Integer.parseInt(line.split(" ")[1]);

        }


    }      

Ref : http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

Rahman
  • 3,755
  • 3
  • 26
  • 43
0

It is as intuitive as using the word split in your question. String class has a split function to split strings using a given parameter.

 import java.io.*;
 public class Read { 
        public static void main(String[] args) throws Exception{

        FileReader file = new FileReader("test.txt");
        BufferedReader reader = new BufferedReader(file);
        String names[] = new String[10];
        int num[] = new int[10];
        String lineSplit[] = new String[2]; 
        for(int i = 0; i<names.length;  i++){
              String line = reader.readLine();
              if(line != null){
                   //splits line using space as the delimeter
                   lineSplit = line.split("\\s+");
                   names[i] = lineSplit[0];
                   num[i] = Integer.parseInt(lineSplit[1]);
              }
        }               
 }
 }
dsh
  • 12,037
  • 3
  • 33
  • 51
digidude
  • 289
  • 1
  • 8