In: Computer Science
Exercises
4. Using the IDE make a new project/program by changing SmallIO.java so that integers instead of Strings are entered by the user.
5. Change the program so that it only loops until the number -999 is entered by the user.
6. Modify the last program so that it (a) keeps and displays a running total and the average so far of the entered numbers (b) displays the largest and the smallest numbers so far of the entered numbers.
NOTE: PART 4 AND 5 HAS BEEN DONE. IN PART 6a TOTAL HAS BEEN DONE YOU HAVE TO CALCULATE AVERAGE AND DO PART B. BELOW IS THE PROGRAM CONTINUE DOING IT FROM WHERE I LEFT. THANKS
package tutorial1;
import java.util.Scanner;
/**
*
* @author ML
*/
public class Tutorial1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = 0; // initialise to empty string
int total = 0;
while (a != -999){
//an infinite loop, use Ctrl-C to quit
System.out.println("Enter a line:"); //prompt
a= keyboard.nextInt(); ///accepts an integer
System.out.println("Your number: " + a);
//method caLLS
total = totalaverage(a, total);
System.out.println("Your total is: " + total);
System.out.println(); // print a blank line
} //end of while
}//end of main
// keeps and displays a running total and the average so far of the
entered numbers
public static int totalaverage(int a, int total)
{
return total + a ;
}
}
If you have any problem with the code feel free to comment.i have highlighted the edited codes.
Program
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
/**
*
* @author ML
*/
public class Test {
public static void main(String[] args) {
Scanner keyboard = new
Scanner(System.in);
int a = 0; // initialise to empty
string
int total = 0;
// arraylist for holding as much valuye as
possible
ArrayList<Integer> list = new
ArrayList<>();
while (true) {
// an infinite
loop, use Ctrl-C to quit
System.out.println("Enter a line:"); // prompt
a =
keyboard.nextInt(); /// accepts an integer
if (a == -999)// quite condition
break;
System.out.println("Your number: " + a);
list.add(a);
// method
caLLS
total =
totalaverage(a, total);
System.out.println("Your total is: " + total);
// showing the average in 2
decimal places
System.out.printf("Average
is: %.2f\n", (double) total / (double) list.size());
// displaying max and min
value
System.out.println("Max value
entered: " + Collections.max(list));
System.out.println("Min value
entered: " + Collections.min(list));
System.out.println(); // print a blank line
} // end of while
}// end of main
// keeps and displays a running total and the average so far of the
entered numbers
public static int totalaverage(int a, int total) {
return total + a;
}
}
Output