我在嘗試運行程序時遇到問題。我的程序應該做的是接收一個數字並將其與int進行比較。我明白,該程序認爲我試圖比較字符串與int並不高興。我能做什麼?運算符<未定義爲參數類型(s)字符串,int
import java.util.Scanner;
public class C {
public static void main(String args[]) {
Scanner input = new Scanner (System.in);
String age = input.nextLine();
if (age < 50){
System.out.println("You are young");
}else{
System.out.println("You are old");
}
}
}
這肯定應該是正確的答案,因爲'input.nextInt'就是要走的路。 –
通過使用['hasNextInt'](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)檢查輸入,可以防止從'Scanner'選項中拋出異常首先是#hasNextInt())。 –
'parseInt()'不是更好的解決這個問題的方法,因爲方法可能會拋出'NumberFormatException' – Andrew