-3
Whoa, guys, blz? First time here and I’m starting to learn Java as my first programming language. Okay, my teacher sent me a challenge to make a simple program that asks the user for an indeterminate amount of integers, and when he finishes entering those numbers, he types some command by a specific string. So far so good, but when I used Try catch to handle the data entry exceptions I ended up going into a looping. I tried for a few hours to figure out what I had to do to fix this, but honestly, I quit. I’m gonna send my code over here so you can see it and give me a light. Ah, remembering that I’ve really started learning Java now, so there’s a lot I don’t know right (including Try-catch itself), I take advice on how to improve.
import java.util.Scanner;
class calculo {
int length = 1; //Tamanho do array
int i = 0; //Contador do índice
void determinaMedia() {
Scanner entrada = new Scanner(System.in);
System.out.println("Digite a quantidade de números desejados");
for(String quebra = "On"; quebra != "Off"; ) {
int numeros[] = new int[length];
try {
numeros[i] = entrada.nextInt(); length++; i++;
} catch(java.util.InputMismatchException e){
String Off = entrada.nextLine();
quebra = Off;
if(quebra == "On") {System.out.println("Erro!");}
}
}
}
}
After all, even after I enter the string the code keeps running endlessly.
Welcome to [en.so]! You have posted an image of the code and/or error message. Although it sounds like a good idea, it’s not! One of the reasons is that if someone wants to answer the question, they can’t copy the code and change something inside. Click on the [Edit] link and put the code/error as text. See more about this in these links - Manual on how NOT to ask questions, Post Error Message as Picture
– Cmte Cardeal
A question, what kind of
for
is that it? Is it normal in Java? It’s very strange....– Cmte Cardeal
I’ve seen a guys using before for a similar exercise, replicated in my code. But I’ve tried to do something different using While, same result.
– JohnPzin
And it worked msm. On the line " break = Off;" put . Intern() after Off, and it finally worked. I’ve had a headache from thinking about it.
– JohnPzin
@Cmtecardeal O
for
has 3 parts separated by;
-for(inicialização; condição; incremento)
. Only none of them is mandatory (an extreme case would befor(;;)
which basically amounts towhile(true)
). In the case of the question, you do not have the third part (since the variable used in the condition is changed within the loop). This is not unique to Java, C was already so for example... Anyway, the problem is that it is comparing strings with==
instead ofequals
(see the dup I indicated). Inclusive, @Johnpzin, useequals
is recommended, alreadyintern
no (read the duplicate above)– hkotsubo
@hkotsubo got it. Comparison of strings had also found it strange. But it was good to refresh the Java times of college:)
– Cmte Cardeal