gpt4 book ai didi

java - 如何忽略 double 但将其余 int 传递到 txt 文件中的数组中?

转载 作者:行者123 更新时间:2023-11-30 01:42:05 24 4
gpt4 key购买 nike

我正在做一个 Java 练习,它要求我读取一个包含数字(包括整数和 double )的文件并将它们循环到一个数组中。但是,下面的代码仅在第一个 double 处停止,然后不再继续。我必须做什么才能跳过该 Double (以及稍后出现的 Double)并继续显示整数?

int index = 0;
Scanner scan1 = new Scanner(new File(fileName));
while(scan1.hasNextInt()) {
index = index + 1;
scan1.nextInt();
}
int[] numbers = new int[index];
Scanner scan2 = new Scanner(new File(fileName));
for(int i = 0; i < index; i++) {
numbers[i] = scan2.nextInt();
}
return numbers;

更新的代码:

public int[] readNumbers2(String fileName) throws Exception {
int index = 0;
Scanner scan1 = new Scanner(new File(fileName));
while(scan1.hasNext()) {
if(scan1.hasNextInt()) {
index = index + 1;
scan1.nextInt();
} else {
scan1.next();
}
}
int[] numbers = new int[index];
Scanner scan2 = new Scanner(new File(fileName));
for(int i = 0; i < index; i++) {
numbers[i] = scan2.nextInt();
}
return numbers;
}

最佳答案

不是一个完整的答案,但这个循环可能更适合您:

while (scan1.hasNext()) {
if (scan1.hasNextInt()) {
// do something with int
} else {
// move past non-int token
scan1.next();
}
}

例如:

public static void main (String args[]) {
Scanner scan1 = new Scanner("hello 1 2 3.5 there");
while (scan1.hasNext()) {
if (scan1.hasNextInt()) {
// do something with int
int i = scan1.nextInt();
System.out.println(i);
} else {
// move past non-int token
scan1.next();
}
}
}

打印:

 1
2

这是基于您更新的代码帖子的版本:

Scanner scan1 = new Scanner("hello 1 2 3.5 there");
int index = 0;
while(scan1.hasNext()) {
if(scan1.hasNextInt()) {
index = index + 1;
scan1.nextInt();
} else {
scan1.next();
}
}

System.out.println("there are "+index+" integer tokens");

int[] numbers = new int[index];
int i = 0;

Scanner scan2 = new Scanner("hello 1 2 3.5 there");
while(scan2.hasNext()) {
if(scan2.hasNextInt()) {
numbers[i++] = scan2.nextInt();
} else {
scan2.next();
}
}

for (int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}

打印

there are 2 integer tokens
1
2

关于java - 如何忽略 double 但将其余 int 传递到 txt 文件中的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593998/

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