[英]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.