Scanner
classWe will be using the Scanner
class for two things in today’s lab:
We will also use while
and for
loops for this short assignment.
Get started by creating a new Java Project on Eclipse, and then a new class (new .java
file) called FileSum
(remember that class names are proper cased):
Proper Case (FileSum) – the first letter of every word, inclusing the first word, is uppercase while the remaining letters are lowercase
Your class should have a main method (that’s what gradescope will be calling), your main method should be public and static
Remember that your class name need to match file name (FileSum.java
)
Scanner
Import the appropriate class at the top of your file:
Then, in your main method, call the constructor:
Print a message to the user, for them to enter a file name (it must match the spelling in the instructions).
Then, read the keyboard input:
Once you have read the user input, you can go ahead and use that user string to read the file.
For this to work, you need a throws FileNotFoundException
in your main method definition.
Your file Scanner
has the following methods:
.hasNextLine()
– returns true if there’s a next line to read, false otherwise.nextLine()
– returns a string for the next line in the fileWrite a while
loop that if there’s a next line to be read in the file, reads it
For each line you read, you can use the following String
methods:
.split(" ")
– split a String by single spaceThis method returns an Array, so when assigning the result of a String split to a variable name, use String[]
type declaration.
Once you’ve created an array of Strings, which are the individual numbers that you need to sum up together, you will iterate over this array with a for loop.
The structure of a for loop in Java is:
for(type variable = start; condition to stop; increment)
For example:
Your limit will be the length of your array, which can be retrieved by its .length
variable
You can use the valueOf()
method from the Integer
class to convert a string to an integer:
Submit your assignment to gradescope
Remember you need to submit the FileSum.java
file
Add package com.gradescope.filesum;
to the top of your file so that the binary file is placed in the correct autograder folder