2017-04-17 11 views
1
ここ

ファイルは、Javaと一致するまで

abcd 
1234 
efgh 
5678 

が含ま

だから私はaccounts.txtしたファイルは

スキャナによるスキャン= NULLを検索するための私のコードです。

try { 
     scan = new Scanner(new File("accounts.txt")); 

    } catch (Exception e) { 

     e.printStackTrace(); 
    } 

    String inpUser; 
    inpUser = usernameTextField.getText(); 

    String inpPass; 
    inpPass = pinNumberTextField.getText(); 

    String user=""; 
    if(scan.hasNextLine()) 
    user = scan.nextLine(); 

    String pass=""; 
    if(scan.hasNextLine()) 
    pass = scan.nextLine(); 

    if (inpUser.equals(user)&& inpPass.equals(pass)){ 
     accountGUI s = new accountGUI(); 
     s.setVisible(true); 
    }else { 
     JOptionPane.showMessageDialog(null,"Wrong Password/Username"); 
    } 

私はプログラムを実行し、入力efgh5678にしようとした場合、それが唯一のaccounts.txtに最初の2行をチェックするので、それは間違ったパスワード/ユーザ名を言うだろう。最初の2行だけでなく、ファイル全体をチェックするようにコードを変更するにはどうすればよいですか?

- 新しい問題 - 私はこの行っている:

String user=""; 
String pass=""; 

while(scan.hasNextLine()){ 
user = scan.nextLine(); 
pass = scan.nextLine(); 
} 

を今、それはaccounts.txtの最初の2行をスキップして

+2

if whileの代わりにすべての行を読み込むwhileループを使用します。 – Omore

+0

@Omoreそれは素晴らしい仕事です。ありがとう – hDDen

答えて

1

最初に、最初の2行だけをチェックするコードがありました。これは、認証しようとするユーザーがファイルの先頭にない場合に問題になりました。第2に、whileループを試しましたが、whileループはファイルのすべての行を最後まで調べて、の最後の行をの2行だけチェックすることはありません。

whileループは正しければ近いですが、行のペアごとに、それがユーザー入力のペアであれば、それらを正常に認証するというチェックを追加する必要があります。次に、ユーザーを見つけたかどうかを追跡します。正しいユーザーを見つけずにファイルの最後に到達すると、エラーメッセージが表示されます。

String user=""; 
String pass=""; 

boolean foundUser = false; // Keeps track of if we found the user's credentials 

while(scan.hasNextLine()) { 
    // get username (we know it is there) 
    user = scan.nextLine(); 

    // Get password, making sure to check it exists! 
    if(scan.hasNextLine()) 
     pass = scan.nextLine(); 

    // If we have found the user's credentials, log in 
    if (inpUser.equals(user) && inpPass.equals(pass)) { 
     accountGUI s = new accountGUI(); 
     s.setVisible(true); 
     foundUser = true; 
     break; // We found the user, stop looping (stop looking) 
    } 
} 

// If we've reached the end of the file, and not found the user 
if(!foundUser) 
    JOptionPane.showMessageDialog(null,"Wrong Password/Username"); 
1

を使用してくださいライン3から開始しますwhileループはファイルからすべての入力を読み込みます。 あなたのコードを見てください:

String user=""; 
if(scan.hasNextLine()) // if statement performs operation only once 
user = scan.nextLine(); // this is the operation to perform once 

String pass=""; 
if(scan.hasNextLine()) // if statement performs operation only once 
pass = scan.nextLine(); // this is the operation to perform once 

あなたは一度だけの行を読んでいます。 if文(1回)の代わりにループ(複数回)を使用してみてください

+0

thats working great。ありがとう – hDDen

+0

あなたの質問に答えた場合は、私の答えを正しいとマークしてください –

+0

私はエラーを発見しました。 私は持っています 'String user =" "; String pass = ""; while(scan.hasNextLine()){ user = scan.nextLine(); pass = scan.nextLine(); } ' 、最初の2行をスキップします。何故ですか? – hDDen

関連する問題