2014-11-15 101 views
1

完成後輸出應該是:從txt文件名(一個字)和(ints)讀取輸入。寫入輸出文件列表,年齡那麼名稱

15 Michael 
16 Jessica 
20 Christopher 
19 Ashley 
etc. 

我並不擅長此道,並希望任何輸入任何關於如何得到由int和字符串打印線線。我避免了數組方法,因爲我總是遇到數組的困難。任何人都可以告訴我,如果我在正確的軌道上,以及如何正確解析或鍵入投入整數,以便他們可以打印到輸出文件的一行?我一直在這工作幾天,任何幫助將不勝感激!這是我到目前爲止。

import java.io.PrintWriter; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class NameAgeReverse 
{ 
    public static void main (String[] args) 
    { 
    System.out.println("Programmed by J"); 
    String InputFileName; 
    String OutputFileName; 

    Scanner keyboard = new Scanner(System.in); 
    System.out.print("Input file: "); 
    InputFileName = keyboard.nextLine(); 

    System.out.print("Output file: "); 
    OutputFileName = keyboard.nextLine();  


    Scanner inputStream = null; 
    PrintWriter outputStream = null; 
     try 
     { 
     inputStream = new Scanner(new FileInputStream("nameAge.txt")); 
      outputStream =new PrintWriter(new FileOutputStream("ageName.txt")); 

    } 
     catch(FileNotFoundException e) 
     { 
      System.out.println("File nameAge.txt was not found"); 
      System.out.println("or could not be opened."); 
      System.exit(0); 
     } 
     int x = 0; 
     String text = null; 
     String line = null; 

     while(inputStream.hasNextLine()) 
     { 
     text = inputStream.nextLine(); 
     x = Integer.parseInt(text); 
     outputStream.println(x + "\t" + text); 
     } 
     inputStream.close(); 
     outputStream.close();   

    } 

    } 

這裏是我的錯誤信息:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Michael" 
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:492) 
    at java.lang.Integer.parseInt(Integer.java:527) 
    at NameAgeReverse.main(NameAgeReverse.java:52) 

回答

0

text = inputStream.nextLine();將閱讀與兩個名字和年齡文字的整條生產線。假設輸入文件中每行的格式爲age name,可以執行以下操作,將每行文本解析爲期望的值。請注意,這不會與其他代碼一起使用。只是一個指針:

text = inputStream.nextLine().split(" "); // split each line on space 
age = Integer.parseInt(text[0]); // age is the first string 
name = text[1]; 
0

這應該工作:

import java.io.IOException; 
import java.nio.charset.Charset; 
import java.nio.charset.StandardCharsets; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
import java.util.ArrayList; 
import java.util.List; 

public class ReadWriteTextFile { 
    final static Charset ENCODING = StandardCharsets.UTF_8; 

    public static void main(String... aArgs) throws IOException{ 

    List<String> inlines = Files.readAllLines(Paths.get("/tmp/nameAge.txt"), ENCODING); 
    List<String> outlines = new ArrayList<String>(); 
    for(String line : inlines){ 
      String[] result = line.split("[ ]+"); 
      outlines.add(result[1]+" "+result[0]); 
    } 
    Files.write(Paths.get("/tmp/ageName.txt"), outlines, ENCODING); 
    } 

} 
相關問題