我正在尝试获得如下所示的输出:
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
1234
5678
9012
3456
789
第一行是数字字符串(行),最后一行是所有以4为增量打印的数字(断路器)。这是到目前为止我得到的代码(由于老师的缘故,我正在使用两个不同的文件或程序)。
import java.util.Scanner;
import static java.lang.System.*;
public class LineBreaker {
private String line;
private int breaker;
public LineBreaker() {
this("", 0);
}
public LineBreaker(String s, int b) {
line=s;
breaker=b;
}
public void setLineBreaker(String s, int b) {
line=s;
breaker=b;
}
public String getLine() {
return line;
}
public String getLineBreaker() {
String box = "";
Scanner chopper = new Scanner(line);
while (chopper.hasNext()){
for (int i=0;i<breaker;i++){
box+=chopper.next();
}
box=box+"\n";
}
return box;
}
public String toString() {
return getLine()+"\n"+getLineBreaker()+"\n";
}
}
(下一个在单独的文件中)
import java.util.Scanner;
import static java.lang.System.*;
public class LineBreakerRunner {
public static void main(String args[]) {
LineBreaker test = new LineBreaker("1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9",4);
System.out.println(test);
}
}
这是我收到的错误消息:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at lab12_scanner_chopper.LineBreaker.getLineBreaker(LineBreaker.java:41)
at lab12_scanner_chopper.LineBreaker.toString(LineBreaker.java:49)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at lab12_scanner_chopper.LineBreakerRunner.main(LineBreakerRunner.java:16)
C:\Users\Harrison\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
该错误指向LingBreaker
中的行,其内容为box+=chopper.next();
,所以我认为问题是我在字符串中添加了切碎的位。但是我真的不明白为什么这是一个问题。我需要使用扫描仪/斩波器才能获得信用。
答案 0 :(得分:0)
对于看来是一个简单问题的代码很多。我将打印String
。我将使用正则表达式删除所有空白。然后,我将迭代输入并一次增加4个字符。喜欢,
String s = "1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9", s1 = s.replaceAll("\\s+", "");
int len = s1.length();
System.out.println(s);
for (int i = 0; i < len; i += 4) {
System.out.print(s1.charAt(i));
if (i + 1 < len) {
System.out.print(s1.charAt(i + 1));
}
if (i + 2 < len) {
System.out.print(s1.charAt(i + 2));
}
if (i + 3 < len) {
System.out.print(s1.charAt(i + 3));
}
System.out.println();
}
输出(按要求)
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
1234
5678
9012
3456
789
如果需要使用Scanner
,则(出于相同的结果),请执行类似的操作
String s = "1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9";
System.out.println(s);
Scanner sc = new Scanner(s);
while (sc.hasNextInt()) {
System.out.print(sc.nextInt());
if (sc.hasNextInt()) {
System.out.print(sc.nextInt());
}
if (sc.hasNextInt()) {
System.out.print(sc.nextInt());
}
if (sc.hasNextInt()) {
System.out.print(sc.nextInt());
}
System.out.println();
}