Concept explainers
Explanation of Solution
Program code:
Test.java
//import the required packages
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
//define a class inputStats
public class Main
{
//define the main
public static void main(String[] args) throws Exception
{
//create the object of File class
File fileName = new File("file.txt");
//create the object of Scanner class to refer the file
Scanner in = new Scanner(fileName);
//call the method negativeSum()
negativeSum(in);
}
//define a method negativeSum()
public static boolean negativeSum(Scanner in)
{
//declare the integer variables "step" and "sum"
int step =0;
int sum = 0;
//declare a boolean variable flag
boolean flag = false;
//iterate a while loop to get the integers
while (in.hasNextInt())
{
//add the tokens to sum
sum+= in.nextInt();
//increment the step by 1
step++;
//if the value of sum is less than 0
if (sum < 0)
{
//set the value of flag as true
flag = true;
//break the condition
break;
}
}
//if the value of flag is true
if (flag)
{
//print the value of sum and step
System.out.println(sum + " after " + step + " steps");
}
//if the value of flag is false
else
{
//print the statement
System.out.println("no negative sum");
}
//return the value of flag
return flag;
}
}
Explanation:
The above snippet of code is used find the negative sum of the values in the given input file...
Want to see the full answer?
Check out a sample textbook solutionChapter 6 Solutions
Building Java Programs: A Back To Basics Approach, Loose Leaf Edition (5th Edition)
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education