[英]Why does random.nextInt() create “IllegalArgumentException: n <= 0: -1”?
[英]Why Does nextInt() Ignore /n?
我遇到了我的代碼問題,幸好我能夠在這里解決另一個類似的問題,但是我很好奇為什么會這樣。
這是我程序的簡化版本:
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
while(!input.equals("x")){
if(input.equals("m")){
String temp = scan.nextLine();
String entry = scan.nextLine();
}
else if(input.equals("f")){
String color = scan.nextLine();
int nothing = scan.nextInt();
}
System.out.println("Enter 'm' for mascara, 'f' for foundation, 'x' to exit");
System.out.println("Entry? :");
input = scan.nextLine();
}
}
使用此代碼,輸入“ m”不會給我任何問題,但是輸入“ f”會使我兩次打印兩次。 為什么恰好發生在nextInt()而不是nextLine()呢?
'm'
Enter 'm' for mascara, 'f' for foundation, 'x' to exit
Entry? :
'f'
Enter 'm' for mascara, 'f' for foundation, 'x' to exit
Entry? :
Enter 'm' for mascara, 'f' for foundation, 'x' to exit
Entry? :
為什么
nextInt()
忽略\\ n?
它不會忽略它。 它只是不讀1 。
實際上, nextLine
方法在這里是異常的。 大多數next
方法的工作方式是獲取下一個令牌,然后嘗試解析令牌。 獲取下一個令牌意味着:
nextLine()
方法是不同的。 它僅讀取直到下一個行尾序列的所有字符。
1-...除非在調用nextInt()
它是領先的定界符之一!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.