0

I was trying to create my first program and I got a problem, my program should work fine but there is an error, in the "While" the instruction R=input.nextLine() doesn't get read and I can't assume why. I used the Scanner Class to do the input. there is the program:

import java.util.*;
    public class Prova {

        public static void main(String[] args) {
            int N,S=0;
            Scanner input = new Scanner(System.in);
            String R;
            System.out.print("Do you want to start? S/N: ");
            R = input.nextLine();
            while(R.equals("S")){
                System.out.print("Digit a Number: ");
                N=input.nextInt();
                S=(S+N);
                System.out.print("Do you want to continue? S/N: ");
                R=input.nextLine();
            }
            System.out.println("Result: "+S);
            input.close();
        }
    }

The program Should do an addiction and ask if you want to add more numbers and then print the result but i get this:

Do you want to start? S/N: S
Digit a Number: 24
Do you want to continue? S/N: Result: 24
  • 1
    [Scanner is skipping nextLine() after using next() or nextFoo()?](//stackoverflow.com/q/13102045) `nextInt` leaves the newline in the input buffer. `nextLine` reads that. Then `R.equals("S")` fails because `R` is an empty string. – Johnny Mopp Sep 13 '18 at 14:51
  • Ok, i found a solution, just do a input.nextLine() (IN MY CASE) right after the nextint and it will work – Giovanni Marciano Sep 13 '18 at 14:57

0 Answers0