6. Write a program that can read three integers from the user and then determines the smallest value among the three integers.
The using of if statement is not the efficient way for the solution. It is better to use an array with loop mainly when there is a list of integer. The following is an algorithm for this program using a flow chart.
The source code:
import java.util.Scanner;
publicclass SmallestNumber { public static void main(String[] args) { int num1, num2, num3, smallest=0;
Scanner readinput = new Scanner(System.in);
System.out.print("Enter three integers: "); num1 = readinput.nextInt(); num2 = readinput.nextInt(); num3 = readinput.nextInt();
// for a list of integers, it is better to use array if((num1 < num2) && (num1 < num3)) System.out.print("The smallest number among "+num1+","+num2+","+num3+" is "+num1); else if((num2 < num1) && (num2 < num3)) System.out.print("The smallest number among "+num1+","+num2+","+num3+" is "+num2); // see a variation here else if ((num3 < num1) && (num3 < num2)) System.out.print("The smallest number among "+num1+","+num2+","+num3+" is "+num3); // exit for none applicable else System.out.println("Not applicable, all input is similar..."); } } |
An output samples:
Enter three integers: 1 2 3 The smallest number among 1,2,3 is 1
Enter three integers: 7 -10 12 The smallest number among 7,-10,12 is -10
Enter three integers: 23 40 20 The smallest number among 23,40,20 is 20
Enter three integers: 25 25 7 The smallest number among 25,25,7 is 7
Enter three integers: 2 2 2 Not applicable, all input is similar... |
7. Write a program that asks the user to input an integer and then outputs the individual digits of the number.
We can use the division (/) and modulus (%).
import java.util.Scanner;
publicclass IndividualInteger { //------------------------------------------------------------------------- // Separating an integer to individual digits // The x % y computes the remainder obtained when x is divided by y. // int % int must evaluate to an int value, while double % int, // int % double, double % double evaluate to a double. // For example, 8 % 3 is 2, 3 % 8 is 3, 8.4 % 3 is 2.4, 8.0 % 2.0 is 3.0 and // 8.4 % 3.1 is 2.2. //-------------------------------------------------------------------------
public static void main(String[] args) { Scanner readinput = new Scanner(System.in);
// can try long for bigger range, int range is the limit int intnumber, condition, remainder; // counter to store the number of digit entered by user int counter = 0;
// prompt user for input System.out.print("Enter an integer number: "); // read and store input in intnumber intnumber = readinput.nextInt(); // set the condition sentinel value to intnumber condition = intnumber;
// we need to determine the number of digit // entered by user, we don't know this and store it in counter while (condition > 0) { condition = condition / 10; counter = counter + 1; }
// well, we already know the number of digit entered by user, // start with number of digits less 1, because we need to discard // the last one, pow(10,1) counter = counter - 1; System.out.println("The individual digits:"); while (counter >= 0) { // extract each of the decimal digits, need to cast to int // to discard the fraction part // pow(10, counter) used to determine the ...,10000, 1000, 100, 10, 1 // because initially we don't know how many digits user entered... remainder = intnumber % (int) Math.pow(10, counter); intnumber = intnumber/(int) Math.pow(10,counter); System.out.print(intnumber +" "); intnumber = remainder; counter = counter - 1; } } } |
An output samples:
Enter an integer number: 273865 The individual digits: 2 7 3 8 6 5
Enter an integer number: 23407721 The individual digits: 2 3 4 0 7 7 2 1
Enter an integer number: 9152 The individual digits: 9 1 5 2 |
8. Write a program that asks the user to input an integer and then outputs the number with the digits reversed.
This is a previous answer with an array to store the integer digits and then read the array reversely.
import java.util.Scanner;
publicclass ReverseIndividualInteger { //------------------------------------------------------------------------- // Separating an integer to individual digits // The x % y computes the remainder obtained when x is divided by y. // int % int must evaluate to an int value, while double % int, // int % double, double % double evaluate to a double. // For example, 8 % 3 is 2, 3 % 8 is 3, 8.4 % 3 is 2.4, 8.0 % 2.0 is 3.0 and // 8.4 % 3.1 is 2.2. //-------------------------------------------------------------------------
public static void main(String[] args) { Scanner readinput = new Scanner(System.in);
// can try long for bigger range, int range is the limit int intnumber, condition, remainder; // counter to store the number of digit entered by user // counter1 is similar, used as for loop sentinel int counter = 0, i =0, j=0, counter1 = 0; int [] reverseint = new int[20];
// prompt user for input System.out.print("Enter an integer number: "); // read and store input in intnumber intnumber = readinput.nextInt(); // set the condition sentinel value to intnumber condition = intnumber;
// we need to determine the number of digit // entered by user and store it in counter while (condition > 0) { condition = condition /10; counter = counter + 1; // this counter for printing in reverse counter1 = counter1 + 1; }
// well, we already know the number of digit entered by user, // start with number of digits less 1, because we need to discard // the last one, pow(10,1) counter = counter - 1; System.out.print("The number in reverse: "); while (counter >= 0) { // extract each of the decimal digits, need to cast to int // to discard the fraction part // pow(10, counter) used to determine the ...,10000, 1000, 100, 10, 1 // because initially we don't know how many digits user entered... remainder = intnumber % (int) Math.pow(10, counter); intnumber = intnumber/(int) Math.pow(10,counter);
// store the digits in an array for later use reverseint[i] = intnumber; i++; // update and repeat for the rest intnumber = remainder; counter = counter - 1; } // print the array element in reverse for(j=counter1-1;j >= 0;j--) System.out.print(reverseint[j]); } } |
An output samples:
9. Write a program that asks the user to enter any number of integers that are in the range of 0 to 30 inclusive and count how many occurrences of each number are entered. Use a suitable sentinel to signal the end of input. Print out only the numbers (with the number of occurrences) that were entered one or more times. (Note: You must use array in your solution for this problem) |
Uses 3 arrays, one for storing the input, one used for comparison to count the occurrences and another on to store the count of occurrences. Display the content of the third array.
import java.util.Scanner;
publicclass IntegerOccurrence { //--------------------------------------------------------- // Count the integer occurrences between 0 and 30 inclusive //---------------------------------------------------------
public static void main(String[] args) { // used to store the input by user int [] myint = new int[50]; // used to compare myint[] to every element for occurrences int [] mycompare = new int[31]; // used to store the count of occurrences, initially all element default to 0 int [] mycount = new int[31]; // array indexes int i = 0, j = 0, k = 0, sum = 0;
// fill in mycompare[] for comparison for(j=0;j <= 30;j++) mycompare[j] = j;
// prompt user for input until stopped do { Scanner readinput = new Scanner(System.in);
System.out.print("Enter integer between 0 and 30 inclusive, other to stop: "); // store user input in myint[] myint[i] = readinput.nextInt();
// do a comparison for(j=0;j<=30;j++) for(k=0;k<=30;k++) { // make sure the index is same j = k; // compare the user input to every mycompare[] values // if similar... if(myint[i] == mycompare[j]) // ...if similar, store the count at similar index of mycompare[] mycount[k] = mycount[k]+1; }
// increase counter for next input i++; // the sentinel range values, minus 1 for the last user input }while(myint[i-1] >=0 && myint[i-1] <= 30); // print the results that already stored in mycount[] System.out.println("Number\tCount"); System.out.println("======\t====="); // iterate all element... for(k=0; k <=30 ;k++) { // …but, just print the number that having count if(mycount[k] != 0) { System.out.println(k+"\t\t"+mycount[k]); sum = sum + mycount[k]; } } System.out.println("Total user input = " + sum); } } |
An output samples:
Enter integer between 0 and 30 inclusive, other to stop: 5 Enter integer between 0 and 30 inclusive, other to stop: 4 Enter integer between 0 and 30 inclusive, other to stop: 3 Enter integer between 0 and 30 inclusive, other to stop: 2 Enter integer between 0 and 30 inclusive, other to stop: 6 Enter integer between 0 and 30 inclusive, other to stop: 1 Enter integer between 0 and 30 inclusive, other to stop: 3 Enter integer between 0 and 30 inclusive, other to stop: 2 Enter integer between 0 and 30 inclusive, other to stop: 4 Enter integer between 0 and 30 inclusive, other to stop: 7 Enter integer between 0 and 30 inclusive, other to stop: 1 Enter integer between 0 and 30 inclusive, other to stop: 2 Enter integer between 0 and 30 inclusive, other to stop: 3 Enter integer between 0 and 30 inclusive, other to stop: 3 Enter integer between 0 and 30 inclusive, other to stop: 4 Enter integer between 0 and 30 inclusive, other to stop: 5 Enter integer between 0 and 30 inclusive, other to stop: 3 Enter integer between 0 and 30 inclusive, other to stop: 2 Enter integer between 0 and 30 inclusive, other to stop: 0 Enter integer between 0 and 30 inclusive, other to stop: 1 Enter integer between 0 and 30 inclusive, other to stop: 6 Enter integer between 0 and 30 inclusive, other to stop: 3 Enter integer between 0 and 30 inclusive, other to stop: -1 Number Count ====== ===== 0 1 1 3 2 4 3 6 4 3 5 2 6 2 7 1 Total user input = 22 |
10. In a gymnastics or diving competition, each contestant’s score is calculated by dropping the lowest and highest scores and then adding the remaining scores. Write a program that allows the user to enter eight judges’ scores and then outputs the point received by the contestant. A judge awards point between 1 and 10, with 1 being the lowest and 10 being the highest. For example, if the scores are: 9.2, 9.3, 9.0, 9.9, 9.5, 9.5, 9.6 and 9.8, then the contestant receives a total of 56.9 points. (Note: You must use array in your solution for this problem)
Store the result in an array and then manipulate them.
import java.util.Scanner; // for double formatting import java.text.DecimalFormat;
publicclass gymnasticScore { //--------------------------------------------------------- // Calculate the gymnastics score //---------------------------------------------------------
public static void main(String[] args) { double maxScore = 0.0, minScore = 0.0, sumScore = 0.0,scoreAvg = 0.0, totalScore = 0.0 ; // used to store 8 scores from 8 judges double[] num = new double[8];
Scanner readinput = new Scanner(System.in); // prompt user for inputs System.out.print("Enter 8 scores out of ten points separated by a space: "); // store all the input in num[] for(int i=0;i<num.length;i++) { num[i] = readinput.nextDouble(); // sum up all the score sumScore = sumScore + num[i]; } // set initial value minScore to the first array element minScore = num[0]; // iterate, compare for max and min score and store them for(int j = 0;j< num.length; j++) { if( minScore > num[j]) { minScore = num[j]; }
if( maxScore < num[j]) { maxScore = num[j]; } } // discard the lowest and highest scores totalScore = sumScore - (maxScore + minScore); // find the average score, the number of scores = 8.0 – 2.0 = 6.0 scoreAvg = totalScore / 6.0; // print all the related information System.out.println("====================================="); System.out.println("Your Lowest score is " + minScore); System.out.println("Your Maximum score is " + maxScore); System.out.println("Your Total point is " + totalScore); // formatting the double output to two decimal places DecimalFormat fmt = new DecimalFormat("0.##"); System.out.println("Your average point is " + fmt.format(scoreAvg)); System.out.println("====================================="); System.out.println("=========CONGRATULATION!============="); } } |
An output samples:
Enter 8 scores out of ten points separated by a space: 9.2 9.3 9.0 9.9 9.5 9.5 9.6 9.8 ===================================== Your Lowest score is 9.0 Your Maximum score is 9.9 Your Total point is 56.9 Your average point is 9.48 ===================================== =========CONGRATULATION!=============
Enter 8 scores out of ten points separated by a space: 8.9 9.7 8.8 10.0 9.5 8.7 9.2 9.1 ===================================== Your Lowest score is 8.7 Your Maximum score is 10.0 Your Total point is 55.2 Your average point is 9.2 ===================================== =========CONGRATULATION!============= |