Reputation:
I need a program that asks the user to introduce up to 10 names (to end, the user could type "fim" [that is end in Portuguese]).
My current problem is how to terminate the program if the user reach 10 names.
Here is my main function:
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Introduza até 10 nomes completos com até 120 caracteres e pelo menos dois nomes com pelo menos 4 caracteres: ");
String nome = keyboard.next();
for(int i = 0; i < 10; i++) {
while(!nome.equalsIgnoreCase("fim") && i<10) {
nome = keyboard.next();
}
}
keyboard.close();
}
Upvotes: 0
Views: 63
Reputation: 3609
You might want to give a try to this code (I have made some explanations in the comments to proper lines):
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Introduza até 10 nomes completos com até 120 caracteres e pelo menos dois nomes com pelo menos 4 caracteres: ");
String nome = keyboard.next();
int i = 0; // Here I instroduce a counter, to increment it after each input given
while(!nome.equalsIgnoreCase("fim") && i!=10) { // stop performing while-loop when nome is equal to "fim"
// or if i==10 (if any of these conditions is false, entire condition is false)
nome = keyboard.nextLine();
i++; // increment counter after input
}
keyboard.close();
System.out.println("End of input"); // Just to confirm that you exited while-loop
}
Upvotes: 1
Reputation: 8598
I am not a big fan of break
, so adding to Frakcool's excellent answer, you can use a do-while
loop instead:
String nome;
int i = 0;
do {
nome = keyboard.next();
i++;
}
while(!nome.equalsIgnoreCase("fim") && i<10);
Also right now you're overwriting all previously entered names. So you either have to handle them directly inside the loop, or collect them in some kind of container, e.g. a list. I would rewrite the loop as such:
String nome;
int i = 0;
while(i<10 && !(nome = keyboard.next()).equalsIgnoreCase("fim")) {
i++;
// Either handle nome here directly, or add it to a list for later handling.
}
Upvotes: 2
Reputation: 11143
You're running into an infinite loop with the while
as is. You want to change it to an if
statement and ask just for fim
and call break;
if that happens.
So it should end as:
for(int i = 0; i < 10; i++) { //This will run 10 times
nome = keyboard.next();
if(nome.equalsIgnoreCase("fim")) { //This will verify if last input was "fim"
break; //This breaks the for-loop
}
}
Or if you really want to use a while
loop inside the for
one (not recommended tho) you need to increase i
inside it:
for(int i = 0; i < 10; i++) {
while(!nome.equalsIgnoreCase("fim") && i<10) {
nome = keyboard.next();
i++;
}
}
Upvotes: 3