本文介紹了使用 nextInt 和 nextLine() 時遇到問題的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
這不是讓我輸入我的名字,但它確實可以正常工作.我知道我可以更改語句的順序,但還有其他方法可以做到嗎?
It's not letting me put my name in but it does the age works fine. I know i can change the order of the statements but is there another way I could do it?
import java.util.Scanner;
public class ScannerErr2
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner(System.in);
String name;
int age;
System.out.print("Enter your age : ");
age= keyboard.nextInt();
System.out.print("Enter your name: ");
name= keyboard.nextLine();
System.out.println("Age : "+age);
System.out.println("Name: "+name);
}
}
推薦答案
你的問題是下一個 int 沒有考慮你名字部分的輸入中的換行符.因此名稱返回為空白.
You problem is that the next int doesn't consider the new line character which goes in the input for your name part. Hence name is returned as blank.
您可以通過 2 種方式更改代碼:
You can change your code in 2 ways:
System.out.print("Enter your age : ");
age = keyboard.nextInt();
keyboard.nextLine();
System.out.print("Enter your name: ");
name = keyboard.nextLine();
或
System.out.print("Enter your age : ");
age = Integer.parseInt(keyboard.nextLine().trim());
System.out.print("Enter your name: ");
name = keyboard.nextLine();
我個人喜歡第二種方式.
I personally like the second way.
這篇關于使用 nextInt 和 nextLine() 時遇到問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!