Mak Haylu
Mak Haylu

Reputation: 25

User enter integer separated by whitespace

int a,b,c,d;

system.out.println("enter number");

a=input.nextInt();

system.out.println("enter number");

b=input.nextInt();

system.out.println("enter number");

c=input.nextInt();

d=(a*b)+c;

system.out.println("the total number is" + d);

My code works but when the user puts the value of a, b, and c it prints on a different line. I want the values to be entered all at once, and separated by whitespace (e.g. 10 11 13) and then calculate. How can I put all of these inputs onto one line, just separated by whitespace then calculate?

Upvotes: 1

Views: 68

Answers (2)

ninja.coder
ninja.coder

Reputation: 9648

I don't see any problem with your code. I think you just have to remove the extra sysouts and it should work fine.

Try this code snippet:

int a,b,c,d;
Scanner input = new Scanner(System.in);
System.out.println("Enter 3 Numbers (Separated By White-space): ");

a = input.nextInt();
b = input.nextInt();
c = input.nextInt();

d = (a*b)+c;

System.out.println("The Total Number: " + d);

Output:

Enter 3 Numbers (Separated By White-space): 1 2 3
The Total Number: 5

Upvotes: 2

hagmic
hagmic

Reputation: 146

The Scanner delimits by space out of the box. The following code should get you what you are looking for.

public static void main(String[] args) {
    Scanner myScanner = new Scanner(System.in);
    System.out
            .println("Please enter three integers separated by white space.");
    int myInt1 = myScanner.nextInt();
    int myInt2 = myScanner.nextInt();
    int myInt3 = myScanner.nextInt();
    int mySum = myInt1 + myInt2 + myInt3;

    System.out.println("The sum of " + myInt1 + " + " + myInt2 + " + "
            + myInt3 + " = " + mySum);

    myScanner.close();
}

The console should display:

Please enter three integers separated by white space.
1 30 45
The sum of 1 + 30 + 45 = 76

Upvotes: 3

Related Questions