如何解决这个java.util.Scanner.next,抛出java.util.NoSuchElementException

时间:2012-04-22 23:02:42

标签: java java.util.scanner jcombobox

我正在过滤新行,但是第一次在第二次循环时它会导致line 2文件失败。

例外:

run:
a[line 1]l[0]
Exception in thread "main" java.util.NoSuchElementException
a[line 2]l[1]
a[line 3]l[2]
b[line 1]l[0]
b[line 3]l[1]
    at java.util.Scanner.throwFor(Scanner.java:855)
    at java.util.Scanner.next(Scanner.java:1364)
    at ui.Test.main(Test.java:82)

代码:

// a) Lines
String a = "line 1\n\r" +
           "line 2\n\r" +
           "line 3\n\r";                
// b) Total length 
int len = 0;    
Scanner sc = new Scanner(a).useDelimiter("\r?\n\r|\\|");
while (sc.hasNext()) {
  System.out.println("a[" + sc.next() + "]l[" +  len + "]" ); 
  len++;
}

// c) Prepare array 
String[] value;
value = new String[len+1];
len = 0;    
sc = new Scanner(a).useDelimiter("\r?\n\r|\\|");
while (sc.hasNext()) {
  System.out.println("b[" + sc.next() + "]l[" +  len + "]" ); 
  value[len] = sc.next();
  len++;
}

// d) Goal - use the value for JComboBox
System.out.println(value);

1 个答案:

答案 0 :(得分:2)

你在第二个循环中调用next两次,调用它一次并存储值:

String val;
while (sc.hasNext()) {
  val=sc.next();
  System.out.println("b[" + val + "]l[" +  len + "]" ); 
  value[len] = val;
  len++;
}