2017-07-02 59 views
-2

我已經制作了這個程序,並且我被卡住了。當我運行它並輸入不使用空格時,它可以正常工作,例如,在客戶輸入中僅輸入Bob。但是,當我輸入Bob White時,它將合併接下來的兩個字符串輸入方向(如附圖所示)。我在這裏做錯了什麼?Java字符串輸入無法正常工作

import java.util.*; 

public class Blah{ 

    public static void main(String[] args){ 

     Scanner in = new Scanner(System.in); 

     String customerName; 
     System.out.println("Enter customer name: ");   
     customerName = in.next(); 

     String customerAddress; 
     System.out.println("Enter customer address: ");   
     customerAddress = in.next(); 

     String customerPhoneNumber; 
     System.out.println("Enter customer phone number: ");    
     customerPhoneNumber = in.next(); 

     in.close(); 
    } 
} 

output

+1

使用'Scanner#nextLine()'(而不是'Scanner#next()')。 –

+0

謝謝Elliott,我是新手,無法爲我的生活制定出我做錯了什麼,歡呼隊友 –

回答

0

那是因爲掃描儀#下一個方法不會消耗您輸入的最後一個換行符,因此該換行到掃描儀#nextLine下次調用消耗

嘗試使用nextLine()方法with trem()方法

customerName = in.nextLine().trim(); 
+0

如果使用int:Integer.parseInt(input.nextLine());或Double.toString(double),如果是double。 –

+0

謝謝@Fady –

+0

不客氣 –

0

您需要閱讀使用nextLine() method然後從領先並使用trim() method結尾的空格修剪整條生產線。

customerName = in.nextLine().trim(); 
customerAddress = in.next().trim(); 
customerPhoneNumber = in.next().trim(); 
相關問題