在userInput.equals("0") ?
部分中,两个结果表达式都返回void类型。为什么然后它告诉我表达式返回String?
import java.util.Scanner;
public class BaseConverter {
private static final int SENTINEL = 0;
public static void main(String args[]) {
askInput();
}
private static void askInput() {
Scanner reader = new Scanner(System.in);
String userInput;
System.out.println("This is converter");
System.out.println("0 to stop");
while(true) {
System.out.print("Enter hex: ");
userInput = reader.nextLine();
userInput.equals("0") ? break : System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
}
}
}
答案 0 :(得分:2)
您必须从三元运算符切换到 if / else 语句
if(userInput.equals("0")) {
break;
} else {
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
}
此代码可以简化为:
if(userInput.equals("0")) {
break;
}
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
答案 1 :(得分:1)
你不能像这样使用三元运算符,而是这样做:
if(userInput.equals("0")) break;
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
答案 2 :(得分:0)
在您的情况下,最好像这样使用do{} while()
循环:
do {
System.out.print("Enter hex: ");
userInput = reader.nextLine();
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
} while (!userInput.equals("0"));
这意味着,重复到userInput
应该等于0
,在这种情况下你不需要使用break
。
要获得更好的解决方案,您仍然需要使用try
和catch
来避免NumberFormatException
:
do {
System.out.print("Enter hex: ");
userInput = reader.nextLine();
try {
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
} catch (NumberFormatException e) {
System.out.println("Incorrect Number");
}
} while (!userInput.equals("0"));