gpt4 book ai didi

java - 如何读取同一包内的文件

转载 作者:行者123 更新时间:2023-12-01 11:08:45 26 4
gpt4 key购买 nike

我创建了一些代码,要求用户输入一个 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"));

关于java - 如何读取同一包内的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32613133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com