review test questions. I need to write a small java program. write code that rea
ID: 3569592 • Letter: R
Question
review test questions. I need to write a small java program.
write code that reads integers from an input file named "infile.txt". the code uses a while loop to read integers from the file until it finds EOF(end of file). For each integer it reads from the file (call it x) code uses a while loop to calculate and print to screen the sum of the squares of every integer from 1 up to x.
The sum is printed only once after it is calculated.
assume all integers are at least 1.
if the file contains no integers code must print "the file has no integers"
MAY NOT USE A FOR OR DO..WHILE LOOP.
example if the file contains only the number 4 the program will print 30
the sum of the square of each number up to x so it would be 1+4+9+16
Explanation / Answer
import java.io.*;
import java.util.*;
class PrintSquare{
public static void main(String [] args){
int flag = 0;
try{
File f = new File("infile.txt");
Scanner s = new Scanner(f);
int num;
while(s.hasNextInt()){
flag = 1;
num = s.nextInt();
int sum = 0;
while(num > 0){
sum += num*num;
num--;
}
System.out.println(sum);
}
if(flag == 0){
System.out.println("The file has no integers");;
}
}catch(IOException e){
e.printStackTrace();
}
if(flag == 0){
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.