本文介紹了使用 nextInt 和 nextLine() 時(shí)遇到問(wèn)題的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
這不是讓我輸入我的名字,但它確實(shí)可以正常工作.我知道我可以更改語(yǔ)句的順序,但還有其他方法可以做到嗎?
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);
}
}
推薦答案
你的問(wèn)題是下一個(gè) int 沒(méi)有考慮你名字部分的輸入中的換行符.因此名稱返回為空白.
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.
您可以通過(guò) 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();
我個(gè)人喜歡第二種方式.
I personally like the second way.
這篇關(guān)于使用 nextInt 和 nextLine() 時(shí)遇到問(wèn)題的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!