2016-05-31 72 views
1

在這個片段中,我正在做三種不同類型的變量並添加它們,然後再打印。Java掃描器不能接受字符串後點擊進入

public static void main(String[] args) { 
    int i = 4; 
    double d = 4.0; 
    String s = "HackerRank "; 
    Scanner scan = new Scanner(System.in);  
    int firstVariable = 0; 
    double secondVariable = 0.0;  
    String theString = ""; 

    firstVariable = scan.nextInt(); 
    secondVariable = scan.nextDouble(); 
    theString = scan.nextLine(); 

    System.out.println(firstVariable+i); 
    System.out.println(secondVariable+d); 
    System.out.println(s+""+theString); 

} 

我儘快提供firstVariable擊球輸入輸入,然後提供輸入爲secondVariable,現在爲我打進入theString被捕獲值(我知道這應該捕獲它)。
編輯:在這種情況下,我應該如何提供輸入到theString而不是與空間

我曾嘗試這樣的事情,

while(scan.hasNext()) 
     theString = scan.nextLine(); 

但它也不能工作。

+0

@Tom不,它不重複,請檢查編輯部分。這些重複鏈接的問題沒有編輯部分的答案。我的意思是處理這兩種情況,即在空間和新線路之後提供輸入。 – piechuckerr

回答

3

只需選中scan.nextLine()是空的,如果這樣再打電話scan.nextLine()爲未來:

secondVariable = scan.nextDouble(); 
theString = scan.nextLine().trim(); 
if (theString.isEmpty()) { 
    theString = scan.nextLine(); 
} 

另一種方法用pattern

firstVariable = scan.nextInt(); 
secondVariable = scan.nextDouble(); 
theString = scan.next("\\w+"); 
+0

請檢查我在我的問題中所做的修改。在這種情況下,如果用戶在'secondVariable'變量輸入後給空間提供'theString',那麼它提供的解決方案將不起作用。 – piechuckerr

+0

我已經更新了我的答案,支持雙字符串 –

+0

@Tunaki Nope問題與通常的方式不同,人們通常想知道不同類型掃描器方法之間的區別 – piechuckerr

1

有兩種方法來解決問題:

第一種是使用

nextLine() 
每次從用戶這樣的閱讀時間

int firstVariable = scan.nextInt(); 
scan.nextLine(); 
double secondVariable = scan.nextDouble(); 
scan.nextLine(); 
String theString = scan.nextLine(); 

第二個是從nextLine()解析整數和double值,如下所示:

int firstVariable = Integer.parseInt(scan.nextLine()); 
Double secondVariable = Double.parseDouble(scan.nextLine()); 
String theString = scan.nextLine(); 
0

你需要你的字符串theString前添加一個額外的scan.nextLine();,捕捉雙後輸入。就像這樣:

firstVariable = scan.nextInt(); 
secondVariable = scan.nextDouble(); 
scan.nextLine(); 
theString = scan.nextLine(); 

只是作爲一個建議,以減少你的代碼,就沒有必要添加這些:

int firstVariable = 0; 
double secondVariable = 0.0;  
String theString = ""; 

只需將類型添加到變量捕捉掃描:

int firstVariable = scan.nextInt(); 
double secondVariable = scan.nextDouble(); 
scan.nextLine(); 
String theString = scan.nextLine();