2013-06-21 1 views
0

프로그래밍 할 준비가 된 Java IDE로 작업하고 있습니다. 내 프로그램에 4 자리 핀 번호를 요청하려고합니다. .txt 파일에 번호를 저장할 수 있지만 콘솔에서 인쇄 할 수 있기를 원합니다. 그래서 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

을 시도 할 수 있지만, 나는 내가 것 (예를 들어, 이클립스와 넷빈즈)를 사용해 다른 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 문은 안전을위한 문이지만 원하는 경우 제거 할 수 있습니다.