Yes, you need to make a loop (in this case, I will wear a while
), and only stop it when a different option than "Sim"
(or when the name entered is "Thanos"
, which is the other condition you said should end the program).
Another detail is that you don’t need to create two instances of Scanner
. That would only make sense if each one was reading from one input stream different, but as both are reading from System.in
, it is only necessary to create a.
And in the specific case of System.in
, don’t need to close it too (read more about this here and here).
Anyway, the code would look like this:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Qual o seu nome?");
if ("Thanos".equalsIgnoreCase(scanner.nextLine())) {
System.out.println("Bem-vindo, pode acabar com geral <3");
break;
} else {
System.out.println("Você não é bem-vindo!\nQuer tentar colocar novamente seu nome?");
if (! "Sim".equalsIgnoreCase(scanner.nextLine())) {
break;
}
}
}
I create a Scanner
at the beginning of the program and use it throughout the loop. As I said before, there is no reason to create another Scanner
to read from it stream (in the case of System.in
). It’s redundant and unnecessary.
while (true)
is a loop infinite, which is only interrupted by the break
. And the break
is called only if the name entered is "Thanos"
, or if something other than "Sim"
in the question "want to try to put your name again" - note that you have a !
before the call to equalsIgnoreCase
, which is the negation operator (ie if
checks that what was typed is not equal to "Sim"
).
Also note that if you just need to check the return of scanner.nextLine()
, and will not use this value for anything else after, nor need to store it in a variable. Just pass the return directly to equalsIgnoreCase
.
But if you’re going to use variables, try to use more meaningful names than t
or n
. For example, they could be called nome
and opcao
, or something like that, which refers to what they actually represent in the code. It may seem like a silly detail, but giving more meaningful names helps a lot at the time of programming.
Recalling that the method equalsIgnoreCase
makes the comparison case insensitive, i.e., without differentiating between upper and lower case. Then the code enters the if("Thanos".equalsIgnoreCase(scanner.nextLine()))
if you type "thanos"
, "THAnos"
, "thANos"
, etc. If you want him to just consider "Thanos"
(just like that, with T
uppercase and the rest lower case), just switch to equals
. The same goes for comparison with "Sim"
.
Thank you so much for the help, I will continue studying through the points mentioned. Again thank you!
– gabresep