How to put Input on next line in Java's Scanner utility

VrnRap picture VrnRap · Sep 12, 2013 · Viewed 17.6k times · Source

I have a basic java question about the scanner utility. Let's say i have a simple program that takes the user input and stores it in a variable. My question is when i run the program that asks for multiple inputs, the cursor starts at the beginning of the question and not after it. My code is:

public class question3 {

    public static void main(String[] args){

       Scanner s = new Scanner(System.in);
       System.out.println("Enter the first number:");
       Float a = s.nextFloat();
       System.out.println("Enter the second number:");
       Float b = s.nextFloat();
       System.out.println("Sum = " + (a+b));
       System.out.println("Difference = " + (a-b));
       System.out.println("Product = " + (a*b));


       }
}

When I run this program it will look like Enter First Number then i type the number, and then |Enter Second Number. "|" meaning where the blinking cursor is. When I type it'll show up underneath, but it could confuse the user so I was wondering what the solution could be.

enter image description here

It is an IDE problem, since nothing else is wrong with the code.

Answer

Josh M picture Josh M · Sep 12, 2013

Instead of println(String) before each input, change it to print(String). So it would look something like this:

public class question3{

    public static void main(String[] args){

        Scanner s = new Scanner(System.in);
        System.out.print("Enter the first number:");
        Float a = s.nextFloat();
        System.out.print("Enter the second number:");
        Float b = s.nextFloat();
        System.out.println("Sum = " + (a+b));
        System.out.println("Difference = " + (a-b));
        System.out.println("Product = " + (a*b));


    }
}

Also, just a note, you should use proper/appropriate naming conventions for your variables. Like for your Scanner, you should call it reader or input; something which represents its function. The same idea goes for the rest of your variables. Also, class names start with a capital.

Here is what the finished result looks like:

enter image description here