根据.txt文件中的信息检查用户输入

时间:2014-11-14 01:30:11

标签: java file validation loops

我正在创建一个我们进行货币兑换的项目。其中一个步骤是我必须让用户输入他们想要从美元转换成什么类型​​的货币。我必须做一个while循环来检查并确保输入对文本文件是正确的。

文本文件只有这个

  

CD 1.05 0.93
  MP 0.11 0.095
  欧盟1.554 1.429

所以这个人会输入CD MP或EU而不确定如何检查它。使用eclipse和txt文件位于项目文件夹中。

public class Communication {
    public String askForCode(){

    String currencyCode = JOptionPane.showInputDialog(null, "We exchange the following Currencies: \n "
            + "CD (Canadian Dollar)\n"
            + "MP (Mexican Peso) \n"
            + "EU (Euro) \n"
            + "Enter the Currency Code"); 

    File myFile = new File("dailyrates.txt");
    while (!currencyCode.equals){

    }
    return currencyCode;

}

我会使用file.next行来验证吗?

2 个答案:

答案 0 :(得分:1)

您可以使用showOptionDialog ...

Options

    Object[] options = {"CD",
        "MP",
        "EU"};
    int n = JOptionPane.showOptionDialog(null,
                    "Enter the FROM Currency Code",
                    "From Currency",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    options[2]);

甚至更具限制性showInputDialog ...

Option

    Object[] possibilities = {"CD", "MP", "EU"};
    String s = (String) JOptionPane.showInputDialog(
                    null,
                    "Enter the FROM Currency Code",
                    "From Currency",
                    JOptionPane.PLAIN_MESSAGE,
                    (Icon)null,
                    possibilities,
                    "CD");

这会将用户可用选项限制为您希望他们使用的选项

有关详细信息,请参阅How to Make Dialogs

您可以阅读文本文件,将值存储在数组ListMap中,并直接在对话框中使用这些代码,以增加灵活性......

答案 1 :(得分:0)

Files.readAllLines(Path, Charset)将读取文件中的行到ArrayList,您可以将其更改为toArray()的字符串数组。您可以使用toPath()将文件更改为路径。然后,您可以将每行的开头与输入的字符串进行比较,直到找到正确的行。

相关问题