2016-05-24 58 views
0

我是一個新的java程序員,在我下面的代碼中,當我嘗試輸入像john smith這樣的員工姓名時,只有john被輸出打印出來。 如果我把使用掃描器類的輸入

System.out.print("Enter Employee Name: "); 
String employeeName = s.next(); 

上述

System.out.print("Enter SEX: ");  
char SEX = s.next().charAt(0); 

這段代碼輸出不是要求我employeename值。並直接打印剩餘的值。

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
**package cs480; 
import java.util.Scanner; 
public class CS480D1_Richa_2_Week2 { 
    public static void main(String [] args){ 
    Scanner s=new Scanner(System.in); 
    System.out.print("Ente Employee ID: "); 
    int employeeId = s.nextInt(); 
    System.out.print("Ente SEX: ");  
    char SEX = s.next().charAt(0); 
    System.out.print("Ente Employee Name: "); 
    String employeeName = s.next(); 
    System.out.println("Employee ID is " +employeeId); 
    System.out.println("Employee Name is " +employeeName); 
    System.out.println("Employee gender is " +SEX); 
    }   

}** 
+1

檢查右側的'Related'部分的分隔符。你會得到你的答案 –

回答

0

請嘗試使用此:

public static void main(String[] args) { 

    Scanner s = new Scanner(System.in); 
    System.out.print("Ente Employee ID: "); 
    int employeeId = s.nextInt(); 
    System.out.print("Ente SEX: "); 
    char SEX = s.next().charAt(0); 
    System.out.print("Ente Employee Name: "); 
    String employeeName = s.nextLine(); 
    employeeName = s.nextLine();// Try to add this line of code 
    System.out.println("Employee ID is " + employeeId); 
    System.out.println("Employee Name is " + employeeName); 
    System.out.println("Employee gender is " + SEX); 

} 
+0

嗨埃裏卡,謝謝你現在它按預期工作。當我只使用String employeeName = s.nextLine();它沒有工作。你爲什麼添加該行? – Learn

+0

這意味着char SEX = s.next()。charAt(0);命令只讀取char值。所以在這一行之後,我們需要讀取s.nextLine();執行'\ n'輸入鍵。在那之後employeeName = s.nextLine();此代碼讀取employeeName的用戶輸入。所以你也可以寫這樣的代碼來清除它:s.nextLine(); String employeeName = s.nextLine(); –

0

嘗試更換代碼

字符串employeeName = scanner.nextLine();

代替

字符串employeeName = scanner.next();

next()只能讀取輸入直到空格。它不能讀取由空格分隔的兩個單詞。另外,next()在讀取輸入後將光標放在同一行中。

nextLine()讀取包含單詞之間空格的輸入(即,它讀取直到行\ n結尾)。一旦輸入被讀取,nextLine()將光標定位在下一行。

0

要麼你可以使用

scanner.nextLine() 

或覆蓋分隔符使用next()的

scanner.useDelimiter("\n"); 
scanner.next(); 
0

Scanner.next()使用白色空間分隔符(佔用空白之前的元素)。

因此,無論使用

Scanner.nextLine() 

或重置使用

Scanner s = new Scanner(input).useDelimiter("\\s*"your delimiter"\\s*");