[英]How to Printout String look like Jagged array 3 elements at a time Java
码:
public static void main(String...args) {
File file = new File("C:\\Users\\Izak\\Documents\\NetBeansProjects"
+ "\\ReadElements\\src\\readelements\\elements.txt");
String s = "";
try (Scanner input = new Scanner(file)) {
input.useDelimiter("\\A");
if (input.hasNext()) {
s = input.next();
}
String[] splitedS = s.split("null");
for (int i = 0; i < splitedS.length; i++) {
System.out.print(splitedS[i]);
}
} catch (Exception e) {
System.out.println(e);
}
}
我的elements.txt
内容:
null null -5 160 2 null null
null 75 80 1 75 160 0 null 75 320 1
null null 155 160 2 null null
235 0 1 235 80 2 235 160 1 null null
我到目前为止的结果:
-5 160 2
75 80 1 75 160 0 75 320 1 <--- String gets printout Like this on Screen
155 160 2
235 0 1 235 80 2 235 160 1
例外结果:
-5 160 2
75 80 1
75 160 0
75 320 1
155 160 2
235 0 1
235 80 2
235 160 1
但我无法达到预期的结果。
任何人都可以帮助我解决这个问题?
我看到两种方法:
A.人工处理:
Scanner scan = new Scanner(new File(yourPath));
int current = 0;
while(scan.hasNext()) {
String next = scan.next();
if(next.equals("null")) {
continue;
}
System.out.print(next+" ");
current++;
if(current == 3) {
System.out.println();
current = 0;
}
}
或B:让regex完成工作:
Scanner scan = new Scanner(new File(yourPath));
String full = scan.useDelimiter("\\A").next().replaceAll("null", "")
.replaceAll("\\s+"," ").trim().replaceAll("([^\\s]+\\s*){3}", "$0\n");
System.out.print(full);
第一个不需要太多评论,而另一个则...
scan.useDelimiter("\\\\A").next()
null
值: replaceAll("null", "")
replaceAll("\\\\s+"," ")
[^\\\\s]+
然后再加上任意数量的空白 \\\\s*
并进行三遍 (...){3}
并将其替换并在同一行$0
后面加上新行(=向其添加新行) tl; dr版本5:每3个字后添加换行符。
编辑:
要更好地理解第5步,可以删除replaceAll("([^\\\\s]+\\\\s*){3}", "$0\\n")
以查看字符串在此“魔术”之前的外观。
它只需要3个单词,并用相同的3个单词替换它们,后跟换行符。 “单词”是指一组非白色字符,后跟一些白色字符。
这是我最喜欢的正则表达式教程 (如果没有它,我会迷路的)
编辑2:
我将举一个$0
的简单示例:
如果您想禁止某些单词,例如foo
和boo
,然后用****
替换,则可以简单地执行text.replaceAll("foo|boo", "****")
但是,如果要通过在其前后加上感叹号来突出显示某些单词(例如java
和regex
), regex
必须使用text.replaceAll("java|regex", "!$0!")
您需要做的是将所有数字都放在一个列表中,然后一次打印三个。
public static void main(String[] args) {
File file = new File("elements.txt");
String text = "";
ArrayList<Integer> allNumbers = new ArrayList<Integer>(); // make a list to store the numbers
try (Scanner fileScanner = new Scanner(file)) {
fileScanner.useDelimiter("\\A"); // make one large token
if (fileScanner.hasNext()) {
text = fileScanner.next();
}
} catch (Exception e) {
e.printStackTrace();
}
Matcher matcher = Pattern.compile("-?\\d+").matcher(text); // pattern for integers (negative included)
while (matcher.find()) {
allNumbers.add(Integer.parseInt(matcher.group())); // add each match (i.e. number) to the list
}
for (int i = 0; i < allNumbers.size(); i++) {
System.out.print(allNumbers.get(i));
if ((i + 1) % 3 == 0) { // if index is a multiple of 3
System.out.println(); // go to the next line
} else {
System.out.print(" ");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.