Reputation: 1695
I have this piece of code here:
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
if (input.nextInt() == 999){
break;
} else {
array[i] = input.nextInt();
}
}
I want to break out of the loop if the user enters 999 inside the array but so far no luck. I tried using break or return false but nothing works. Does anyone have a solution? Much thanks!
Upvotes: 0
Views: 3468
Reputation: 213253
You are reading twice inside your loop. So, if your if
condition is falsy (user does not enter 999
), then it will go into else
block where you are reading a new input from user, which can possibly be 999
.
Change your loop to:
for (int i = 0 ; i < array.length; i++ ) {
int read = input.nextInt();
if (read == 999) {
break;
}
array[i] = read;
}
Apart from that, you should also consider the case where user doesn't actually passes an integer, in which case, your code will blow. You can use Scanner#hasNextInt()
method for that.
for (int i = 0 ; i < array.length; i++ ) {
while (!input.hasNextInt()) {
System.out.println("You must pass an integer");
input.next(); // Advance the scanner past the current line.
}
int read = input.nextInt();
if (read == 999) {
break;
}
array[i] = read;
}
Of course, that loop might run forever if user keeps on entering non-integer values. To overcome that, you can give user a maximum number of attemps. That I'll leave up to you to handle. (HINT: You will need a counter that goes from 0 to max. On each loop iteration, reset it).
Upvotes: 4
Reputation: 26
Try this thing in your for loop.
for (int i = 0 ; i < array.length; i++ ) {
int number = input.nextInt();
if (number == 999){
break;
}
System.out.println("aghsdgha" + number);
}
This is the simpler and cleaner way to check the input number.
Upvotes: 1
Reputation: 881463
The way you currently have it is that you're calling nextInt()
multiple times within each iteration.
That means you'll lose data. Let's say you first enter 7. That's picked up in the if
statement as "not 999" so it moves onto the else
clause where you ask the user for yet another number (you've lost the 7).
In addition, you'll only break out of that loop if you enter 999 when it's executing the first call to nextInt()
. If you enter 999 when it's executing the second call, it will just store it and keep going.
Try this instead:
for (int i = 0 ; i < array.length; i++ ) {
int next = input.nextInt();
if (next == 999)
break;
array[i] = next;
}
Upvotes: 3
Reputation: 8473
You are using input.nextInt();
twice.That is reading from console in if
and else
.
for (int i = 0 ; i < array.length; i++ ) {
int enteredNumber = input.nextInt();
if (enteredNumber == 999){
break;
} else {
array[i] = enteredNumber ;
}
}
Upvotes: 5