簡體   English   中英

Java不會從文件讀取int

[英]Java won't read an int from a file

我試圖從文件中讀取字符串,但效果很好,但不能與整數一起使用。 我似乎找不到問題

public static void main(String[] args) throws FileNotFoundException  {

   File in = new File ("FCITsamba.in.rtf");
    Scanner scanner = new Scanner(in);// Scanner variable to read from the input file
    File outFile = new File("FCITsamba.txt");// the out file 
    PrintWriter out = new PrintWriter(outFile); // Printwriter to write to the file

   int maxAccounts = 0;//maximum number of accounts that can be in the bank
   int maxTransactions = 0;//maximum number of transactions in a given day
   int accNum = 0;
   int transNum = 0;
   int d = 0;
   int k = 0;
   int dayNo = 1;


    if (!in.exists()) {
        System.out.println("Input file, " + in + ", does not exist.");
        System.exit(0);
    }


   maxAccounts = scanner.nextInt();
   maxTransactions = scanner.nextInt();
   d = scanner.nextInt(); //representing the number of days for the simulation
   k = scanner.nextInt();

它給了我這個錯誤:

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.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
 at fcitsamba.FCITsamba.main(FCITsamba.java:43)
Java Result: 1

我嘗試放置一個inputMismatchException,但是它不起作用,我也嘗試將其放在if語句中,如下所示:

if(scanner.hasNextInt()){
   maxAccounts = scanner.nextInt();
   maxTransactions = scanner.nextInt();
   d = scanner.nextInt(); //representing the number of days for the simulation
   k = scanner.nextInt();
  }

但是效果不佳

這是輸入文件:

200
10000
2
11
OPENACCOUNT 1485 Aslam Saeed 2000.0
DEPOSIT 1485 1000.0
...

掃描程序一次讀取1個值,因此,如果您嘗試讀取的下一個值不是int,它將拋出錯誤。

我使用了您的數據,以下數據對我有用:

public static void main(String[] args) {
    //Replace FILE_PATH with your file path.
    try {
        Scanner reader = new Scanner(new File("FILE_PATH/fromFile.txt"));
        PrintWriter writer = new PrintWriter(new File("FILE_PATH/toFile.txt"));

        int maxAccounts = reader.nextInt();
        int maxTransactions = reader.nextInt();
        int d = reader.nextInt();
        int k = reader.nextInt();

        writer.println("maxAccounts: " + maxAccounts);
        writer.println("maxTransactions: " + maxTransactions);
        writer.println("d: " + d);
        writer.println("k: " + k);

        writer.close();
        reader.close();
    } catch (FileNotFoundException ex) {
        System.out.println("Error: " + ex.getMessage());
    }
}

當您從文件中讀取文件時,它將無法識別是在讀取數字還是字符串,因此所有內容都將被視為字符串,包括數據文件中顯示的內容(200, 10000, 2, 11)

而不是寫:

d = scanner.nextInt(); 

嘗試這個:

d = Integer.parseInt(scanner.nextLine()); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM