2017-06-19 118 views
0

我正在获取所需的输出,但我的代码尚未完成运行。 我曾用“/”作为分隔符扫描仪类和我的代码是扫描仪类输入不以分隔符结尾

Scanner scan = new Scanner(System.in);   
scan.useDelimiter("/"); 
while(scan.hasNext()) 
{ 
    System.out.println(scan.next()); 
} 

我输入的是我在输出窗口给出的

Input 
abcdef/ghijkl/out/ 

Output: 
abcdef 
ghijkl 
out 

而且程序仍在运行。

+0

你确定有多少串(每串由“/”分隔),你必须阅读? – cse

回答

-2

您在使用scan.close();

在这里你会用它来关闭扫描作为

Scanner scan = new Scanner(System.in);   
scan.useDelimiter("/"); 
while(scan.hasNext()) 
{ 
    System.out.println(scan.next()); 
    scan.close(); 
} 
+1

抛出'IllegalStateException' – bradimus

+2

永远不会这样做,它会关闭'System.in'并使其在程序的其余时间内不可用。 –

1

问题是与next()方法。以下是从Oracal Website其中指出此方法可能阻塞在等待输入信息进行扫描,即使hasNext以前调用()返回真

公共下一字符串()

摘录查找并返回此扫描程序中的下一个完整标记。完整的令牌前后有与分隔符模式匹配的输入。 即使先前调用hasNext()返回true,此方法也可能在等待输入进行扫描时阻塞。

2
import java.util.Scanner; // headers MUST be above the first class 

// one class needs to have a main() method 
public class HelloWorld 
{ 
// arguments are passed using the text field below this editor 
    public static void main(String[] args) 
    { 
    Scanner scan = new Scanner("abcdef/ghijkl/out/");   
    scan.useDelimiter("/"); 
    while(scan.hasNext()) 
     { 
      System.out.println(scan.next()); 
     } 
    } 
} 

这个工程。

您的问题可能是您打开了键盘(System.in)的扫描仪,但没有将键盘输入的值存储在任何地方。你可能会想你的输入设置为变量,就像我已经教会了Java类一直在做:

Scanner scan = new Scanner (System.in); 
String input = scan.nextLine(); // input: "abcdef/ghijkl/out/" 

String[] stringArray = input.split("/"); 
for(String i : stringArray) 
{ 
    System.out.println(i); 
} 
+0

我删除了我发布的最后一个代码片段。这是不正确的。 –