If Else error in java code
I'm getting an error at the line
else break;
I think it might have to do with the location of the "{}"
public class Palindrome {
private static String number;
public static void main(String[] args) {
display();
}
private static int getUserInput() {
int inputNumber = 0;
String answer = JOptionPane.showInputDialog(null, "Please enter a five digit number","Enter a number");
inputNumber = Integer.parseInt(answer);
if(number.length() !=5 ){
JOptionPane.showMessageDialog(null,"Please enter a 5 digit number!","Try again",
JOptionPane.PLAIN_MESSAGE);
else break;
}
return inputNumber;
}
private static boolean check(){
int inputNumber = getUserInput();
int number = inputNumber;
int[] myArray = new int[5];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = (int) (number /(Math.pow(10,i)) % 10);
}
if(myArray[0] == myArray[4] && myArray[1] == myArray[3])
return true;
else
return false;
}
public static boolean display(){
开发者_如何学运维 if (check() == true) {
JOptionPane.showMessageDialog(null, "This number is a Palindrome",
"Excellent!",JOptionPane.INFORMATION_MESSAGE);
} else
JOptionPane.showMessageDialog(null,
"Number is not a Palindrome!",
"Sorry",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
Thanks
else
cannot be part of if
. So, change this -
if(number.length() !=5 )
{
JOptionPane.showMessageDialog(null,"Please enter a 5 digit number!","Try again",
JOptionPane.PLAIN_MESSAGE);
}
else break;
Also, I don't understand why you use break
here ?
if(/*some condition*/){
}else{
break;//invalid use of break it won't compile see below
}
you are writting else
without matching if
moreover you can't break
without loop
or switch case
Also a note: code like "if (condition) return true; else return false;" can be substituted for "return condition;". Much cleaner.
There are two problems:
- else statement is not associated with an if statement. You need to move it outside of the {} for the else
- You are using a break outside of a while or for loop (or named statement).
If you are trying to exit the application, then you can use System.exit method. However a better approach is to return a value that states that the user did not select a value, e.g., -1 or null (change return type of method to Integer).
You cannot break;
from a method, instead you must return from a method. However in your case it would appear you want a retry loop.
private static int getUserInput() {
while(true) {
String answer = JOptionPane.showInputDialog(null, "Please enter a five digit number","Enter a number");
if(answer.length() == 5 )
return Integer.parseInt(answer);
JOptionPane.showMessageDialog(null,"Please enter a 5 digit number!","Try again",
JOptionPane.PLAIN_MESSAGE);
}
}
精彩评论