![](/img/trans.png)
[英]How do I get my Hangman Java file to read a random word in from a .txt file?
[英]How do I get my program to read my txt file in Java?
該程序的一般功能是從txt文件中提取所有信息,將其輸入到數組中,然后將用戶輸入的ID與輸入到數組中的ID進行比較,並返回true或false。 我寫了程序,但是得到了InputMismatchException。 將函數放在try / catch語句中時,運行該函數時將返回null。
這是我的驗證器類:
import java.util.Scanner;
import java.io.*;
public class Validator
{
private int[] valid = new int[18];
public Validator(String filename) throws IOException
{
try
{
File file = new File(filename);
Scanner inputFile = new Scanner(file);
int index = 0;
while (inputFile.hasNext())
{
valid[index] = inputFile.nextInt();
index++;
}
inputFile.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
public boolean isValid(int number)
{
int index = 0;
boolean found = false;
while (!found && index < valid.length)
{
if (valid[index] == number)
{
found = true;
}
index++;
}
return found;
}
}
至於主要方法:
import java.util.Scanner;
import java.io.*;
public class ChargeAccountModification
{
public static void main(String[] args) throws IOException
{
int number;
Scanner keyboard = new Scanner(System.in);
System.out.println("Brandon Woodruff 12/3/16");
System.out.print("Enter your charge account number: ");
number = keyboard.nextInt();
Validator validator = new Validator("AccountNumbers.txt");
if (validator.isValid(number) == true)
{
System.out.println("That's a valid account number.");
}
else
{
System.out.println("That's an INVALID account number.");
}
}
}
最后是txt信息。 將該txt文件稱為AccountNumbers.txt。
5658845 4520125 7895122 8777541 8451277 1302850 8080152 4562555 5552012 5050552 7825877 1250255 1005231 6545231 3852085 7576651 7881200 4581002
實際上,它們每個都出現在列表中各自的行上,但是我似乎無法使其顯示出來。
在此代碼中:
while (inputFile.hasNext()) {
valid[index] = inputFile.nextInt();
index++;
}
嘗試用hasNextInt()
替換hasNext()
hasNextInt()
:
while (inputFile.hasNextInt()){
valid[index] = inputFile.nextInt();
index++;
}
否則,它將讀取空白,並且空白不是數字。
如果不起作用,也可以使用帶空格的定界符:
Scanner s = new Scanner(file).useDelimiter("\\s");
請在輸入時提供堆棧跟蹤。 我用5658845嘗試了相同的程序。 我得到以下回應
Brandon Woodruff 16/12/3輸入您的收費帳號:5658845這是有效的帳號。
但是如果我輸入“ CDCD”。 我得到你的例外。 因此,請檢查您的輸入。 正是掃描儀引發此異常
Brandon Woodruff 12/3/16
Enter your charge account number: CDCD
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at ChargeAccountModification.main(ChargeAccountModification.java:15)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.