gpt4 book ai didi

java - 为什么 hasNextInt() 在这里返回 false ?

转载 作者:行者123 更新时间:2023-12-01 19:45:26 24 4
gpt4 key购买 nike

我有这样的文件 MatrixToCsv.csv:

<小时/>
67,85,20,87,78,46,66;
33,66,88,24,90,28,19;
76,22,46,33,10,16,73;
16,79,28,98,67,49,62;
85,75,12,18,92,58,80;
59,89,16,10,52,67,35;
54,66,62,53,39,91,37;
<小时/>

我想将它保存到一个数组中,但只保存整数,所以我写了这个:

<小时/>
public static void main(String[] args) throws IOException {

Scanner input = new Scanner (new File("MatrixToCsv.csv"));
int rows = 7;
int columns = 7;
int[][] array = new int[rows][columns];

input.useDelimiter(Pattern.compile(",|;|(\\n)"));
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < columns; ++j)
{
if(input.hasNextInt())
{
array[i][j] = input.nextInt();
}
}
}

for(int i = 0; i < rows; i++) {
for (int j = 0; j < array.length; j++) {
System.out.print(array[i][j]+ " ");
}
System.out.println();
}
input.close();
}

输出是:

<小时/>
 67 85 20 87 78 46 66 
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
<小时/>

我想知道为什么它只读取文本中的一行。谢谢。问:

最佳答案

input.useDelimiter(Pattern.compile(",|;|(\\n)"));

在这里,您基本上是在说分隔符可以是一个单个逗号OR一个单个分号OR一个单个换行符。

在每行的末尾都有分号和换行符,这不是您设置扫描仪用作分隔符的内容。使用 [,;\\n]+ 代替,这意味着“,, ;\n 之间的一个至少重复一次”。这样您也将匹配 ;\n

input.useDelimiter(Pattern.compile("[,;\\n]+"));

See it in action

关于java - 为什么 hasNextInt() 在这里返回 false ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53557093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com