[英]How do I read integers from a text file containing integers and strings in java programming?
我只需要读取整数并将它们从文件中求和。 我不知道如何“跳过”字符串或绕过它们只读取整数。 所以这是我的代码,我在本章中的唯一选项是while (!scan.hasNextInt())
。 这是我的代码,减去我刚刚添加的行,它适用于只有整数的文件。 该文件如下所示:
1
2
John
3
4
Black
5
Jason
7
8
每行都有一个数字或一个字符串。 我不明白如何使用这种方法。
我的代码:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
int number;
int temp;
int i;
boolean isPrime = true;
double count = 0.0;
double total = 0.0;
File inputFile = new File("Values.txt");
Scanner file = new Scanner(inputFile);
while (file.hasNext())
{
if (!file.hasNextInt()) { //this just added
String s = file.nextLine(); //added
} //added
else { //added
number = file.nextInt();
}
for (i = 2; i <= (number / 2); i++)
{
temp = number % i;
if (temp == 0)
{
isPrime = false;
break;
}
}
if (isPrime) {
//System.out.println(number);
total = total + number;
count = count + 1.0;
}
isPrime = true;
}
//System.out.println(total);
//System.out.println(count);
System.out.println(total / count);
System.out.println("File is Empty");
file.close();
}
}
我认为问题在于您使用的是nextLine()
而不是next()
。
public static void main(String[] args) {
String s = "1 Hello 1 World 2 3 Hello 7";
Scanner sc = new Scanner(s);
while (sc.hasNext()) {
if (!sc.hasNextInt()) {
sc.next();
} else {
System.out.println(sc.nextInt());
}
}
}
我只需要读取整数并将它们从文件中求和。 我不知道如何“跳过”字符串或绕过它们只读取整数。 所以这是我的代码,我在本章中的唯一选项是while (!scan.hasNextInt())
。 这是我的代码,减去我刚刚添加的行,它适用于只有整数的文件。 该文件如下所示:
1
2
John
3
4
Black
5
Jason
7
8
每行有一个数字或一个字符串。 我不明白如何使用这种方法。
我的代码:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
int number;
int temp;
int i;
boolean isPrime = true;
double count = 0.0;
double total = 0.0;
File inputFile = new File("Values.txt");
Scanner file = new Scanner(inputFile);
while (file.hasNext())
{
if (!file.hasNextInt()) { //this just added
String s = file.nextLine(); //added
} //added
else { //added
number = file.nextInt();
}
for (i = 2; i <= (number / 2); i++)
{
temp = number % i;
if (temp == 0)
{
isPrime = false;
break;
}
}
if (isPrime) {
//System.out.println(number);
total = total + number;
count = count + 1.0;
}
isPrime = true;
}
//System.out.println(total);
//System.out.println(count);
System.out.println(total / count);
System.out.println("File is Empty");
file.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.