maria
maria

Reputation: 288

How to stop input in Java

I'm using NetBeans 8.2 on Ubuntu. Is there any way to make s.hasNextDouble() returns false using keyboard input, so that the last line of the code is executed, without changing the code? This code snippet calculates the average of the entered numbers.

double sum = 0;
int n = 0;

Scanner s = new Scanner(System.in);
System.out.print("Enter 1 number: ");

while (s.hasNextDouble()) {
    double number = s.nextDouble();

    sum += number;

    n++;

    System.out.print("Enter " + (n + 1) + " number: ");
}

System.out.println();
if (n == 0) {
    System.out.println("Error!!!");
} else {
    System.out.println("Average: " + sum / n);
}

Upvotes: 2

Views: 3850

Answers (2)

Svyatoslav Shilkov
Svyatoslav Shilkov

Reputation: 56

So, there are different ways to do this.

First way, the nearest to yours, is to simulate EOF with pressing CTRL+D as mentioned here How to send EOF via Windows terminal (I've tried, it realy works)

Second way is to think about some flag. For example, read until your number isn't -1 or SIMPLY ENTER SOME CHARACTER or something NOT DOUBLE or INT.

Third way is to read line by line, separate numbers using String[] nums = yourLine.split("\\s"); and than just go through your splited string array until Double.parseDouble(nums[i]) will throw exception

That's ways i could remember now. Good luck ;)

Upvotes: 1

Radiodef
Radiodef

Reputation: 37845

hasNextDouble returns false if the next token can't be interpreted as a double, so you can break that loop by entering something that's not a number. This could be anything like for example x, abc or !.

An example of running the program would be:

Enter 1 number: 3
Enter 2 number: 6
Enter 3 number: x

Average: 4.5

Process finished with exit code 0

You could change the message to something like:

System.out.print("Enter " + (n + 1) + " number, or anything else to end: ");

Upvotes: 2

Related Questions