2013-06-21 77 views
0

我正在使用java IDE準備編程。我試圖讓我的程序要求輸入一個4位數的PIN碼。我可以將該數字存儲在.txt文件中,但我希望能夠在控制檯中打印出來。所以假設你的PIN碼是1234,它將被存儲在一個名爲Bank_Pin.txt的文件中,你可以寫一些代碼讓你打印出來。這裏是我使用的存儲號碼是什麼:.txt閱讀器和打印機

    int pinnum = c.readInt(); 
        System.out.println ("Now creating the text fle Bank_Pin.txt."); 
        TextOutputFile a; 
        a = new TextOutputFile ("Bank_Pin.txt"); 
        System.out.println ("Writing text file!"); 
        a.println (pinnum); 
        a.close(); 
        System.out.println ("Done!"); 

這是擺while循環和內如果別人如果問你是否已經有一個代碼語句。如果不是,則會提示您繼續。但是如果你這樣做,我正在努力做到這一點,所以你可以打印出代碼並將其與輸入的代碼進行比較。

回答

0

我從來沒有在IDE準備好。但是我在網上找到了下面的代碼。你可以試試這個

Console c = new Console(); 
c.print("Your PIN Data"); 
+0

不知道這是諷刺還是不好,但一個好的方式.... – Conor

0

我從來沒有合作過「準備程序」,但我認爲它會迴應如下代碼我已經使用會(如Eclipse和NetBeans的)任何其他IDE。看起來你需要ScannerPrintWriter類來讓你的生活更輕鬆。 Scanner類很適合檢查文件是否存在,用PrintWriter類來寫出文件。這就是說,我會嘗試這樣的事情:

while(true){ 
    Scanner fromFile, fromUser = new Scanner(System.in); 
    boolean exists = false; 
    int pin; 

    try{//Attempts to open the file "Bank_Pin.txt" and read in a saved pin 
     fromFile = new Scanner(new File("Bank_Pin.txt")); 
     pin = fromFile.nextInt(); 
     exists = true; 
    } catch (FileNotFoundException e) { 
     System.out.println("No saved pin exists"); 
    } finally {//Closes open resources 
     if(fromFile != null) 
      fromFile.close(); 
    } 

    if(!exists) {//If there isn't a saved pin 
     System.out.print("Please input a pin: "); 
     while(true) {//Ask for a pin until a valid one is given 
      try{ 
       pin = sc.nextInt(); 
       if(String.valueOf(pin).length() != 4)//pin given isn't 4 digits 
        throw new InputMismatchException(); 
       break; 
      } catch (InputMismatchException e) { 
       System.out.print("\nPin input was not valid. Please reinput: "); 
      } 
     } 
     PrintWriter out = new PrintWriter(new File("Bank_Pin.txt)); 
     out.println(pin); 
     out.close(); 
     System.out.println("\nPin has been saved: " + pin); 
    } else { 
     System.out.println("Saved pin: " + pin); 
    } 

    fromUser.close();//Close input from keyboard 
} 

希望這是你在找什麼。所有try-catch-finally語句都是出於安全目的,但如果需要,可以將其刪除。