0

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();
}
Kyle A
  • 928
  • 7
  • 17
  • What is the problem ? That code asks 10 times – azro Mar 15 '18 at 21:48
  • no need for `&& i<10` and as is you're taking all the user input but you'll only maintain the last one. do you want to store it into some array or list? – Ousmane D. Mar 15 '18 at 21:49
  • *Unrelated:* `for` and `while` are not *functions*, but *statements*, more precisely loop-statements. – Andreas Mar 15 '18 at 21:49
  • 4
    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 – Frakcool Mar 15 '18 at 21:49
  • He asks to introduce until the user digits "fim" but besides that if the user introduce 10 name the program should end –  Mar 15 '18 at 21:50
  • If i cant use a while statement how would I do with if? –  Mar 15 '18 at 21:52
  • 1
    Already told you how, use an `if` statement instead. (Look at my answer below) – Frakcool Mar 15 '18 at 21:53
  • Could I add more questions to this one? –  Mar 15 '18 at 22:29

3 Answers3

3

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++;
    }
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • 1
    Remove the `! `, otherwise it breaks on anything but "fim". Otherwise +1 – Max Vollmer Mar 15 '18 at 21:53
  • 1
    Minor edit needed. The `if` should read `if(nome.equalsIgnoreCase("fim"))` without the `!`. – Kyle A Mar 15 '18 at 21:53
  • I could only introduce two name (?) –  Mar 15 '18 at 21:53
  • @CatarinaMota see the updated answer in the first code-block, it had a `!` at the beginning of the `if` statement, remove it and you should have it right now. If this answer solved your question be sure to [accept it](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Frakcool Mar 15 '18 at 21:55
  • Just one more question –  Mar 15 '18 at 21:55
  • 1
    To downvoter, could you explain why the reason for it? So I can improve my answer. Thanks – Frakcool Mar 15 '18 at 21:56
  • How would I limit the user in characters (like until 120 characters )? –  Mar 15 '18 at 21:56
  • @Catarina, The `for` loop repeats. That's what makes it a loop. The code `for(int i = 0; i < 10; i++)` means "repeat the next piece of code as long as `i < 10` and perform `i++` each time the code is run." – Kyle A Mar 15 '18 at 21:56
  • 1
    @CatarinaMota you can use [`String#length()`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()) method. Like `if (nome.length >= 120) { //Do whatever you want here if length is more than or equals 120 }` and be sure to accept the answer if it solved your question – Frakcool Mar 15 '18 at 21:58
  • could I limit in the moment of the user is tipping? –  Mar 15 '18 at 22:01
  • No, this validation needs to be done after user has typed `Enter` key. There's no way to limit user input while typing in a console / terminal based application @CatarinaMota – Frakcool Mar 15 '18 at 22:02
  • Ok I'll keep it. Thank you. –  Mar 15 '18 at 22:32
  • You're welcome @CatarinaMota, be sure to accept the answer that solved your problem. If you keep without accepting answers in your questions, people will be less likely to help you in the future... it also helps to tell other people that your question was already solved :) Good luck – Frakcool Mar 15 '18 at 22:34
  • I'll do it. Thank you for your time. –  Mar 15 '18 at 22:36
2

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.
}
Max Vollmer
  • 8,412
  • 9
  • 28
  • 43
1

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
}
Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
  • 2
    It's always good to explain what the code does, the explanation is more valuable than the code most of the times. – Frakcool Mar 15 '18 at 22:01
  • @Frakcool Of course you're right, in most cases I first try to post a code to make OP have a look at it and get used to it, before I prepare an edit with explanations given (I'm currently preparing it). Thank you for your suggestion. – Przemysław Moskal Mar 15 '18 at 22:04
  • @Frakcool I edited my answer with proper explanations - you might want to have a look at it. – Przemysław Moskal Mar 15 '18 at 22:11
  • I had already upvoted your question because you show another approach to solve the question :) – Frakcool Mar 15 '18 at 22:14
  • @Frakcool Thanks, now I'm thinking of how to achieve limiting user input right in the console. I'll notify you if I find some way to do it. – Przemysław Moskal Mar 15 '18 at 22:16
  • Glad that I could help! – Przemysław Moskal Mar 15 '18 at 22:28
  • @Frakcool Seems like there is no easy way (I thought there will be one) to achieve retrieving each character as user inputs them, but it's possible. Some valuable informations are included here: https://stackoverflow.com/q/1066318/8116173 – Przemysław Moskal Mar 16 '18 at 09:50
  • @CatarinaMota see what the recommended link above this comment from PrzmyslawMoskai says about reading each character but I think it's too much effort for a simple task – Frakcool Mar 16 '18 at 14:43