搜索文本文件以获得特定的双倍

时间:2011-11-06 19:57:03

标签: java

我正在为Comp Sci类编写一个银行帐户程序,并且需要在.txt文件中搜索用户输入的帐号(这是一个int),然后拉出下一行即余额。即用户输入帐号#12345679,我需要取出它的余额。下面是txt文件的示例

12345678
133.87
12345679
500.00
12345670
123.00

到目前为止,我已经和我知道我将不得不如何在if语句中取得平衡

while (accountTries < 3)
        {
            System.out.println("Please enter your 8 digit account number");
            accountNumber = console.next();
            accountLength = accountNumber.length();
            while (in.hasNextInt())
           {
                line = in.hasNextInt();
                if (accountLength == 8 && line == accountNumber  )
                    {
                    accountTries = 3;           
                    }
            }
            System.out.println("INVALID ACCOUNT NUMBER.");
            accountTries++;
            }
        }//End of while loop

3 个答案:

答案 0 :(得分:0)

不确定你要做什么......但这似乎不对:

line = in.hasNextInt(); 

你不应该在这里获得价值吗?你只是在测试是否有任何东西,就像你在“while”条件下那样。

答案 1 :(得分:0)

outer: while (accountTries < 3)
{
    System.out.println("Please enter your 8 digit account number");
    accountNumber = console.next();
    accountLength = accountNumber.length();
    while (in.hasNextLine())
   {
        line = in.nextLine();
        result = in.nextLine();
        if (accountLength == 8 && line.equals(accountNumber))
            {
            accountTries = 3;           
            break outer;
            }
    }

    System.out.println("INVALID ACCOUNT NUMBER.");
    accountTries++;
    }
}//End of while loop

我使用带标签的休息时间离开了外面(你可以用if语句和一个完成标志做同样的事情,但我在这里懒得去做)

答案 2 :(得分:0)

您可以简单地将文件读取到String并按行分隔符(\ n或\ n \ r)拆分。 例如:

String fileContent = //read String from file;
String[] elements = fileContent .split("\n");

for(int i =0; i< elements.length; i++){

if(i%2 ==0){ 
   //get account number
}else{
  //get balance
}

}