1

我正在过滤新行,但它第一次在第二个循环上工作时,它的归档失败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);
4

1 回答 1

1

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

String val;
while (sc.hasNext()) {
  val=sc.next();
  System.out.println("b[" + val + "]l[" +  len + "]" ); 
  value[len] = val;
  len++;
}
于 2012-04-22T23:06:22.563 回答