Reputation: 263
I have created some code that will ask a user to enter in a int value that will then be passed to my first method called parity(). Parity() will then tell the user if it is an odd or even int. After that method finished i want my main program to open my file that is within the same package as my program but my exception keeps getting set off terminating my program with the output "File was not found or could not be opened" I feel like this is a simple fix but much of what i am trying isn't changing it for the better. Here is my code so far:
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);
}
}
Upvotes: 0
Views: 3757
Reputation: 26
I'm not sure I understood the question right, however I can tell you that you can read a file which is in your same package with:
BufferedReader reader = new BufferedReader(new InputStreamReader(Assignment01.class.getResourceAsStream("numbers.txt"), "UTF-8"));
Upvotes: 1