HELP! Part 1: Write a program that instantiates a Scanner object, inputFile, and
ID: 3642381 • Letter: H
Question
HELP!Part 1:
Write a program that instantiates a Scanner object, inputFile, and reads a series of integers from the file. Determine whether or not the sum starting from the first number is ever negative. Produce a message indicating whether or not a negative sum is possible.
For example, suppose the file contains the following integers:
38 4 19 -27 -15 -3 4 19 38
Your will consider the sum of just one number (38), the sum of the first two numbers (38 + 4), the sum of the first three numbers (38 + 4 + 19), and so on up to the sum of all of the numbers. None of these sums is negative, so the message:
No negative sum detected.
is produced.
Now suppose the file contained the following integers:
14 7 -10 9 -18 -8 17 42 98
You find that a negative sum is reached after adding 6 numbers together (14 + 7 + -10 + 9 + -18 + -8) and that the sum is -6. You should exit your loop and report the following:
Negative sum after 6 steps: sum = -6
To determine when there is no more input, use:
inputFile.hasNextInt()
Part 2:
Write a program that will read a text file of integers and output the largest and the smallest value to the screen. You can assume that the file contains nothing but integers.
Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class NegativeSum {
public static void main(String[] args) {
Scanner in;
File file = new File("input.txt");
try {
in = new Scanner(file);
boolean found = false;
int sum = 0;
int count = 0;
while(in.hasNextInt() && found == false) {
sum += in.nextInt();
count++;
if(sum < 0) {
found = true;
}
}
if(found) {
System.out.println("Negative sum after " + count + " steps: sum = " + sum);
}
else {
System.out.println("No negative sum detected");
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MaxAndMin {
public static void main(String[] args) {
Scanner in;
File file = new File("input.txt");
try {
in = new Scanner(file);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
while(in.hasNextInt()) {
int num = in.nextInt();
if(num > max) {
max = num;
}
if(num < min) {
min = num;
}
}
System.out.println("Smallest value: " + min);
System.out.println("Largest value: " + max);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.