根据JAVA中数组中的值,将文件中的值存储在数组中
大家好,我是java新手。我想写一个程序,通过一种特定的方式读取文件。我的文件混合了字符串和整数。 在第一行中有一个数字,告诉我们后面有多少行。 在此之后,每行中都会有一个字符串和一个int。int值会告诉我们这行中有多少个值。 例如: 文本文件:根据JAVA中数组中的值,将文件中的值存储在数组中,java,arrays,file,Java,Arrays,File,大家好,我是java新手。我想写一个程序,通过一种特定的方式读取文件。我的文件混合了字符串和整数。 在第一行中有一个数字,告诉我们后面有多少行。 在此之后,每行中都会有一个字符串和一个int。int值会告诉我们这行中有多少个值。 例如: 文本文件: 2 Coffee 2 Water 200 cofe 300 SweetCoffee 3 Water 200 cofe 300 Sugar 10 我想在不同的数组中传递值 nameOfProduct[0]=Coff
2
Coffee 2 Water 200 cofe 300
SweetCoffee 3 Water 200 cofe 300 Sugar 10
我想在不同的数组中传递值
nameOfProduct[0]=Coffee
nameOfProduct[1]=SweetCoffee
numofIngredients[0]=2
element[0][0]=water
element[0][1]=cofe
element[1][3]=sugar
我试图找到一种有效的方法。这就是我到目前为止所做的
package pkg1;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
int count=0;
int i,j,noIngredients;
public void openfile() {
try {
x = new Scanner(new File("MyRecipes.txt"));
}
catch(Exception e) {
System.out.println("could not find the file");
}
}
public void readFile() {
i=0;
int numofRecipes = x.nextInt();
String nameOfProduct[] = new String[numofRecipes];
int numofIngredients[] = new int[numofRecipes];
while (x.hasNext()) {
// String line = x.nextLine();
nameOfProduct[i] = x.next();
numofIngredients[i] = x.nextInt();
noIngredients=numofIngredients[i];
String element[][] = new String[numofRecipes][noIngredients];
int quantity[][] = new int[numofRecipes][noIngredients];
System.out.printf("%s %d ",nameOfProduct,numofIngredients);
j=0;
while( x.hasNext() || x.hasNextInt()) {
element[i][j] = x.next();
quantity[i][j] = x.nextInt();
System.out.printf("%s %d ",element[i][j],quantity[i][j]);
j++;
}
i++;
x.nextLine() ;
}
}
}
更改此选项:while(x.hasNext()| | x.hasNextInt())
to:
for(int k=0;k您可以使用scanner类检查类型。在此处写入x。下一步()
您可以在此处写入:
if(x.hasNextInt()
int k=x.nextInt()
else字符串s=x.next()
您可以随时检查类型,更多类型可以检查java库。我将创建一个名为Recipe的对象,其中包含成分。它将大大简化操作,而不是使用一堆匹配的数组。