2015-07-13 61 views
0

我是java的新手,需要一些幫助。我寫了這個代碼,但它跳到結束,不要讓我在寫東西控制檯..無法從鍵盤讀取字符串(Java)

import java.util.Scanner; 

public class Exercise21 { 
    public static void main(String[] args){ 

     Scanner keyboardInput = new Scanner("System.in"); 
     String text = ""; 
     String text2 = ""; 

     System.out.println("Type any text : "); 
     if(keyboardInput.hasNextLine()) text = keyboardInput.nextLine(); 

     System.out.println("Type the word you want to find : "); 
     if(keyboardInput.hasNextLine()) text2 = keyboardInput.nextLine(); 

     System.out.println("Your word was found : " + text.indexOf(text2,0)); 

    } 
} 
+5

「System.in」不應該在引號內 – smoggers

+0

我注意到,tkank你! – Gabriel

回答

1

的原因,跳到最後是因爲在開始時,keyboardInput內部沒有任何內容,導致以下2項檢查失敗:

簡單地刪除if檢查將解決您的問題,然後af你可以進行檢查以確保輸入不是空的。或者,您可以將每個輸入封裝在while循環中。

do { 
    text = keyboardInput.nextLine(); 
} while (!text.equals("")) 

如果該值爲空字符串,它將繼續詢問輸入。

0

像這樣,計劃將等待3個輸入下面。

Scanner in = new Scanner(System.in); 
int n,r,c; 
n = in.nextInt(); 
r = in.nextInt(); 
c = in.nextInt(); 

對字符串使用in.nextLine()

0

因爲您的文本尚未輸入,所以您的掃描儀找不到任何方法hasNextLine()(從文件中讀取文本時,此方法非常有用)。

,如果你想等待用戶輸入文本使用 text = keyboardInput.nextLine(); 並取出if聲明

PS:因爲對方說,你應該也有Scanner keyboardInput = new Scanner(System.in);沒有「