-1
public static void main(String[] arg) {
    System.out.println("Enter the pairs: ");
    Scanner kbd = new Scanner(System.in);
    while(kbd.hasNextLine() ) {
        int input1 = kbd.nextInt();
        int input2 = kbd.nextInt();
        maxcycle(input1,input2); 
    }   
}  

Hello,

The code given above is taking one line at a time and I am pasting this in input:

1 10

100 200

201 210

900 1000

It is supposed to read each line, take each integer and put it in input1 and input2 and call method maxcycle. However, the scanner isn't reading the last line.

*kbd.lastLine() isn't working because I don't want a string. I want int.

please help, thanks.

Community
  • 1
  • 1
Fahad Ali
  • 1
  • 1

4 Answers4

0

You can use hasNextInt method

 while(kbd.hasNextInt() )
    {
    int input1 = kbd.nextInt();
    int input2 = kbd.nextInt();
AR KA
  • 13
  • 5
0

It's because even after you call nextInt() twice on the last line, hasNextLine() is still true because the last \n is still in the input stream. So you should or add nextLine() like so:

while(kbd.hasNextLine()) {
    int input1 = kbd.nextInt();
    int input2 = kbd.nextInt();
    kbd.nextLine();
    maxcycle(input1,input2);
}

Or replace hasNextLine() by hasNextInt():

while(kbd.hasNextInt()) {
    int input1 = kbd.nextInt();
    int input2 = kbd.nextInt();
    maxcycle(input1,input2);
}
Maljam
  • 6,244
  • 3
  • 17
  • 30
  • I've done both of these, still giving the output: Enter the pairs: **1 10 100 200 201 210** input **1 10 20 100 200 125 201 210 89** output 900 1000** this is input too but it stays like this and comes after the whole output and doesn't get computed – Fahad Ali Mar 30 '16 at 07:26
0

Please try to add System.out.println statements in for loop to verify that all the inputs are captured.

Example:

System.out.println("input1:"+input1);
System.out.println("input2:"+input2);
maxcycle(input1,input2);
0

This method:

kbd.hasNextLine()

Returns false when the current is the last line to be read, so according to your condition, the last line is not processed. You could change the condition to make sure last line is processed correctly, or read the last two elements outside the while block.

An alternative, if you know exactly the format of the input, for example, supposing first line is the size of a bidimensional array, you can read all numbers according to that...

Scanner s = new Scanner(System.in);
// Read first number
long i = s.nextLong();
long j = s.nextLong();
for (long i1 = 0; i1 < i; i++) {
    for (long j1 = 0; j1 < j; i++) {
        long n1 = s.nextLong();
        long n2 = s.nextLong();
        // Do something with n1 and n2... 
    }
}
Jorge
  • 1,136
  • 9
  • 15