我正在尝试将文件读入程序,然后获取 fileIn 对象并对它们进行计算以创建一个新变量,特别是读取价格并计算销售税。我以前做过这种类型的程序,我是按照下面的代码来做的。出于某种原因,这次我在运行程序时在控制台中收到此错误消息。
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at TaxCalculator.main(TaxCalculator.java:42)
到目前为止,我发现 .next() 方法给了我错误,因为我可以用 .nextLine(); 完整地阅读,但这违背了程序的目的。
import java.io.FileInputStream;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class TaxCalculator {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner fileIn = null; //Initializes fileIn to empty
//Declares variables
String text;
int value;
double price;
double tax;
try
{
//Attempt to open the file
fileIn = new Scanner (
new FileInputStream ("Basket.txt"));
}
catch (FileNotFoundException e)
{
//This block executed if the file is not found
//then the program exits
System.out.println("File not found.");
System.exit(0);
}
//Read and print in lines
value = fileIn.nextInt();
text = fileIn.next();
price = fileIn.nextDouble();
tax = (price * .10);
System.out.printf("%1d %2s %3.2f", value, text, price );
/**
//Read and print next input line
value = fileIn.nextInt();
text = fileIn.next();
price = fileIn.nextDouble();
tax = (price * .10);
System.out.printf("%-7s %20s %22s %30.2f %n", value , text, text,
price);
//Read and print next input line
value = fileIn.nextInt();
text = fileIn.next();
price = fileIn.nextDouble();
tax = (price * .10);
System.out.printf("%-7s %18s %22s %30.2f %n", value , text, text,
price);
**/
// Close file
fileIn.close();
System.out.println("\nEnd of Tax Calculator");
}
}
任何帮助将不胜感激,谢谢。-编辑 - Basket.txt 的内容
1 item at 10.49
1 special item at 13.99
1 candy bar at 0.75
Input 2:
1 imported pack of cigarettes at 10.00
1 imported bottle of alcohol at 44.50
Input 3:
1 imported bottle of alcohol at at 25.99
1 bottle of alcohol at 15.99
1 packet of cough drops at 4.99
1 box of imported cigarettes at 9.25