tags:

views:

66

answers:

4

I am having a problem reading inputs, can anyone help me.

Each line of the input have to Integers: X e Y separated by a space.

12 1    
12 3  
23 4  
9 3 

I am using this code in java but is not working, its only reading the first line can anyone help me?

    String []f; 
    String line;
    Scanner in=new Scanner(System.in);

    while((line=in.nextLine())!=null){
        f=line.split(" ");

        int X,Y;
        X=Integer.parseInt(f[0]);
        Y=Integer.parseInt(f[1]);

        if(X<=40 && Y<=40)
          metohod(X,Y); 


        line=in.nextLine();

    }
}
+1  A: 

You are calling nextLine twice, once in the while, anotherone linha = xxx; what is linha anyways? Try this

BufferedReader reader = new BufferedReader(...);
while((line = reader.readLine())!=null) {
  String[] f = line.split(" ");
  int X,Y;
  X=Integer.parseInt(f[0]);
  Y=Integer.parseInt(f[1]);
}
krico
even with this code it only reads the first line.
please add a printline to the line. It is possible that you are using a unix file (with \n at the end) and reading it in windows (expecting \r\n).
krico
A: 
line=in.nextLine();

You are reading the next line and doing nothing with it. If you remove that it should work.

npinti
Sorry about this, it was a mistake when i was changing the code for you to understand better, i've change it already.
Yeah I thought so :). Anyways, if you remove that line you should be ok.
npinti
A: 

You're calling one line=in.nextLine() too much, but why not use in.nextInt()? The following should work as expectd:

Scanner in = new Scanner(System.in);

while(in.hasNextLine()) {
    int x = in.nextInt();
    int y = in.nextInt();

    if(x <= 40 && y <= 40)
        method(x, y); 
}

(The code is tested, and it reads more than just the first line. Your previous problem could perhaps be the new-line format of the input file.)

Have a look at the scanner API docs.


To debug this you could use the Scanner(File file) constructor instead.

aioobe
I've also tried to use this code and it also only gave me de result for the first line of input. I don't know what is wrong :(
I suspect it has to do with how you feed the input to the program. Try instantiating the scanner using `in = new Scanner(new File("yourfile.txt"));` instead (for debugging).
aioobe
A: 

Since you are using Scanner, why don't you just use nextInt() instead of nextLine()? That way you could call nextInt() twice and get the two numbers for each line.

The way you coded it looks as if you are trying to use a BufferedReader instead of a Scanner.

MAK