2015-07-13 62 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);没有“