我创建了一些代码,要求用户输入int值,然后将其传递给我的第一个方法parity()。然后,Parity()会告诉用户它是奇数还是偶数。该方法完成后,我希望我的主程序打开与程序位于同一程序包中的文件,但我的异常不断出现,并终止输出“找不到文件或无法打开文件”的程序是一个简单的修复程序,但是我尝试的大部分操作并没有使它变得更好。到目前为止,这是我的代码:
package davi0030; import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; public class Assignment01 { static void parity(int value){ int finalValue = value % 2; if (finalValue == 0){ System.out.println(value + " is an even int!"); } else{ System.out.println(value + " is an odd int!"); } } static void findPair(int value2, Scanner inputStream){ int total; int n1 = inputStream.nextInt(); while (inputStream.hasNextLine()){ total = 0; int n2 = inputStream.nextInt(); total = n1 + n2; if (total == value2){ System.out.println("a pair is found: " +n1 + " and " +value2+ " add to " + total); System.exit(0); } System.out.println("no pair in the file adds to" + total); } } public static void main(String[] args) { int value1; int value2; Scanner inputStream = null; Scanner keyboard = new Scanner(System.in); System.out.println("Enter a positive integer, 0 to end:"); value1 = keyboard.nextInt(); while (value1 != 0){ parity(value1); System.out.println("Enter a positive integer, 0 to end:"); value1 = keyboard.nextInt(); } if (value1 == 0){ System.out.println("Congratulations, you passed the first test"); try{ inputStream = new Scanner(new FileInputStream("numbers.txt")); } catch (FileNotFoundException e) { System.out.println("File was not found or could not be opened"); System.exit(0); } System.out.println("file opened successfully"); System.out.println("Enter a positive integer"); value2 = keyboard.nextInt(); findPair(value2, inputStream); } keyboard.close(); System.exit(0); } }
我不确定我是否理解正确的问题,但是我可以告诉你,您可以使用以下方法读取同一包中的文件:
BufferedReader reader = new BufferedReader(new InputStreamReader(Assignment01.class.getResourceAsStream("numbers.txt"), "UTF-8"));