Let's get started with a input/output program!
Open Eclipse
Right-Click on your cs4hs.sp18..your-username
Choose: File -> New -> class
In the Name:
textbox type: InputOutput
Click: Finish
Copy the InputOutput.java
Template (Java) code (below)
Paste that code into your new InputOutput class in the editor
Change both occurrences of put-your-username-here
Replace the blank on the
Scanner
line with:
Scanner(System.in)
After the
// add a line here to output a message advising the user to enter 9999 to exit
comment line add:
System.out.println( "Enter '9999' to exit" ); // informs user how to exit
Replace the blank after the
if (num == 9999) {
line with:
break;
Replace the blank on the
if ()
line with:
cnt > 0
Replace the blank on the
ave =
line with:
sum / (double) cnt;
Replace the blank after the
} else {
line with:
ave = 0;
Click the Run icon
InputOutput.java
Template (Java)
package cs4hs.sp18..put-your-username-here ;
/**
* File: InputOutput.java
*
* Write a program that accepts 10 integers from the keyboard and
* computes their average.
* If the user enters 9999, the program exits early, and outputs
* the average of the numbers entered so far.
*
* Fill in the blanks to make the program work
*
*/
/**
*
* @author put-your-name-here
*
*/
import java.util.Scanner;
public class InputOutput {
public static void main( String args[] ) {
double ave = 0 , cnt = 0 , num = 0 , sum = 0 ;
Scanner sc = new _____________ ;
System.out .println("Integer Averaging Program" );
System.out .println("Enter 10 Integers" );
// add a line here to output a message advising the user to enter 9999 to exit
______________ // prompt the user for up to 10 integers
for ( int i = 1; i < 11; i++ ) {
System.out .print("Enter Integer " + i + ": " );
// check if the user entered a non-integer
if (!sc.hasNextInt()) {
// System.err will print the message in RED
System.err .println("Sorry, please enter an integer" );
sc .nextLine();
i--;
continue ;
}
num = sc .nextInt();
// break out of the loop if the exit code (9999) is entered
if (num == 9999 ) {
__________
}
cnt ++;
sum = (double ) sum + (double ) num ;
}
// check to make sure the count is not set to zero since you can not divide by zero
if (__________ ) {
ave = _____________ ;
} else {
// if the count is zero then the program sets the average equal to zero
____________ ;
}
System.out .println("The average of "
+ cnt
+ " numbers is "
+ ave );
sc.close();
}
}
InputOutput
Class Output
Integer Averaging Program
Enter 10 Integers
Enter 9999 to exit
Enter Integer 1: k
Sorry, please enter an integer
Enter Integer 1: 55
Enter Integer 2: 66
Enter Integer 3: 77
Enter Integer 4: 88
Enter Integer 5: 9999
The average of 4.0 numbers is 71.5