Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PLEASE FIX THE ERROR IN THIS JAVA PROGRAM RepetionTest. java import java.io.File

ID: 440164 • Letter: P

Question

PLEASE FIX THE ERROR IN THIS JAVA PROGRAM




RepetionTest.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class RepetionTest {

public static void main(String[] args) {

Scanner inScanner = new Scanner(System.in);
int sum = 0;

//using while loop
while(true) {
System.out.println("Enter a no. (To exit enter -1):");
int n = inScanner.nextInt();
if(n==-1)
break;
else if(n%2==0)
sum += n;

}

System.out.println("Sum when read from keyboard is " + sum);
fileTest();
}
public static void fileTest() {
try {
Scanner inScanner = new Scanner(new File("C:\Cramster\RepetionTest\src\data.txt"));
int sum = 0;
//using do-while
do {

int n = inScanner.nextInt();
if(n==-1)
break;
else if(n%2==0)
sum += n;

}while(true);
System.out.println("Sum when read from a file is " + sum);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
Output:
Enter a no. (To exit enter -1):
1
Enter a no. (To exit enter -1):
4
Enter a no. (To exit enter -1):
2
Enter a no. (To exit enter -1):
5
Enter a no. (To exit enter -1):
7
Enter a no. (To exit enter -1):
8
Enter a no. (To exit enter -1):
-1
Sum when read from keyboard is 14
Sum when read from a file is 20


Explanation / Answer

Scanner inScanner = new Scanner(new File("C:\Cramster\RepetionTest\src\data.txt")); //this line is looking for file in this directory. CHange your directory of data.txt?

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote