2016-03-28 114 views
2

我試着從我的input.txt文件中解析字符串,但是我得到每次拋出的NumberFormatException異常。我已經添加了迄今爲止所有的代碼。 我也嘗試過.trim。我對Java中的文本文件非常陌生;因此,我不知道這裏有什麼問題。但是,任何幫助將不勝感激。如何在JAVA中解析來自文本文件的輸入?

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.InputMismatchException; 
import java.util.NoSuchElementException; 
import java.util.Scanner; 

public class Lab5_Exceptions_Redo extends Exception { 

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

     String file = "inputt.txt"; 
     String file1 = "outputt.txt"; 
     String file2 = "errorr.txt"; 

     PrintWriter errorr = new PrintWriter(file2); 

     PrintWriter inputt = new PrintWriter(file); 
     inputt.println(15951); 
     // int whatever = Integer.parseInt(file); 
     // System.out.print(whatever); 
     inputt.close(); 
     Scanner scan = new Scanner(file); 
     String number = scan.nextLine(); 
     int num = Integer.parseInt(number.trim()); 
     System.out.printf("%d", num); 

     PrintWriter outputt = new PrintWriter(file1); 
     outputt.println(num); 
     outputt.close(); 
     // inputt.close(); 

     scan.close(); 
     // System.out.printf("%d", num); 

     try { 

     } catch (InputMismatchException e) { 
      errorr.println("There was an input mismatch error."); 
     } catch (NoSuchElementException e) { 
      errorr.println("There is no such element."); 
     } catch (UnsupportedOperationException e) { 
      errorr.println("An unsupported operation occured."); 
     } catch (NumberFormatException e) { 
      System.out.println(e.getMessage()); 
      e.printStackTrace(); 
     } 
     errorr.close(); 

    } 
} 
+0

你嘗試調試的問題?當你嘗試打印'num'時,你看到了什麼? – TheLostMind

回答

4

你犯了一個錯誤。在Scanner的構造函數中,你應該通過File對象而不是String對象。既然你傳遞字符串「inputt.txt」它試圖解析這個字符串,結果你得到了NFE。 試試這個

Scanner scan = new Scanner(new File(file));

0

在做nextLine()的同時,您必須在輸入時輸入空格。使用trim()函數可以消除任何空格。

int num = Integer.parseInt(number.trim()); 

或者,你可以嘗試使用nextInt()代替nextLine()

這裏是parseInt()的JAVA文件:

將字符串參數作爲有符號的十進制整數。字符串中的字符必須全部爲十進制數字,但第一個字符可能是ASCII減號' - '('\ u002D')以指示負值或ASCII加號'+'('\ u002B')。表示一個正值。返回結果整數值,就像參數和基數10作爲parseInt(java.lang.String,int)方法的參數一樣。

+0

我試過了.trim,不幸的是它不起作用。我在用Java創建文本文件方面很新穎,這就是我爲什麼不會從輸入文本文件解析整數的原因而非常困惑的原因。 – SlackStack

+0

這不是真正的根本原因 – Rehman