我想获取一个包含字符串和整数的文本文件,并在每一行上单独获取某些整数,并将该特定整数分配给变量,以便稍后由其他类访问。这是我到目前为止,我几乎肯定它不会起作用:
public void openInputFile()
{
String fileName = "concerts.txt";
Scanner inputStream = null;
try{
inputStream = new Scanner(new File(fileName));
}
catch (FileNotFoundException e)
{
System.out.println("error");
System.exit(0);
}
while (inputStream.hasNextLine()){
int capacityM =0 ;
int ticketPriceM = 0;
int capacityO = 0;
int ticketPriceO = 0;
int capacityP = 0;
int ticketPriceP = 0;
if (inputStream.equals("Maroon 5")){
capacityM = inputStream.nextInt(); //I want to read line #2 of the txt file assign it here
ticketPriceM = inputStream.nextInt();//Line 3 of txt file needs to be assigned here
}
else if(inputStream.equals("One Direction")){
capacityO = inputStream.nextInt(); //
ticketPriceO = inputStream.nextInt();
}
else {
capacityP = inputStream.nextInt();
ticketPriceP = inputStream.nextInt();
}
System.out.println(capacityM + ticketPriceM + capacityO +
ticketPriceO + capacityP + ticketPriceP);
}
inputStream.close();
}
}
这是正在读取的文本文件的样子。我不确定我是否应该使用数组。
Maroon 5
15 //number of tickets available
40 //ticket price
One Direction
10
50
Pearl Jam
20
30
答案 0 :(得分:0)
您应该使用nextLine
方法从文件中读取行。而不是使用equals
方法来比较String
else-if
String line=inputStream.nextLine();//Call nextLine only once
//than use the line to compare
//different condition
if (line.equals("Maroon 5")){
....
}else if(line.equals("One Direction")){
.....
}