我有这个程序,我必须使用它检查用户输入的值是否存在于我在源文件中创建的文本文件中。但是,每次我尝试使用 IOException 调用该方法时,它都会引发错误。请帮帮我谢谢。
import java.util.*;
import java.io.*;
public class chargeAccountModi
{
public boolean sequentialSearch ( double chargeNumber ) throws IOException
{
Scanner keyboard= new Scanner(System.in);
int index = 0;
int element = -1;
boolean found = false;
System.out.println(" Enter the Charge Account Number : " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length )
{
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for ( index = 0 ; index < tests.length ; index ++ )
{
if ( tests[index] == chargeNumber )
{
found = true;
element = index;
}
}
return found;
}
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
object1.sequentialSearch(chargeNumber);
}
catch (IOException ioe)
{
}
System.out.println(" The search result is : " + object1.sequentialSearch (chargeNumber));
}
}
最佳答案
查看您的方法equentialSearch后,一切都好。但尝试改变主要:
但请记住,在您的 Names.txt 文件中,您应该只有数字,因为您使用了 scanner.nextInt();
,因此应该只有数字,否则方法将抛出异常 InputMismatchException。
还要检查 Names.txt 文件的路径,您应该将其放在类路径中,因为您在代码中使用相对路径 File file = new File ("Names.txt");
Names.txt 应位于同一文件夹中。
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
System.out.println(" The search result is : " + object1.sequentialSearch(chargeNumber));
}
catch (IOException ioe)
{
System.out.println("Exception!!!");
ioe.printStackTrace();
}
}
关于java - 调用带有 IOException 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22118184/