I am trying to write a program that takes a set of 10 numbers from the user, finds the smallest and largest value within the set, and displays it to the user. I kind of got the program to work but I am experiencing an issue. It looks like it skips through the first number and assigns the second number to be the smallest value. In class we haven't gotten to arrays yet so, I have to assume that the first value entered in the smallest and largest value Here's what I have:
int smallestValue;
int largestValue;
int numInput;
int counter = 1;
int numSets = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a set of 10 numbers: ");
numInput = input.nextInt();
smallestValue = input.nextInt();
largestValue = input.nextInt();
counter++;
while (counter != 9)
{
numInput = input.nextInt();
counter++;
if (numInput > largestValue)
{
largestValue = numInput;
}
else if (numInput < smallestValue )
{
smallestValue = numInput;
}
}
System.out.println( "Smallest is " + smallestValue );
System.out.println("Largest is " + largestValue);
Thanks in advance!
It skips value because you call input.nextInt() before the loop, you don't need to, and use Integer.MAX_VALUE and Integer.MIN_VALUE to initialize the min and max. Also when you iterate depending on a counter, it's commonly with a for loop
int numInput;
int smallestValue = Integer.MAX_VALUE;
int largestValue = Integer.MIN_VALUE;
Scanner input = new Scanner(System.in);
System.out.print("Enter a set of 10 numbers: ");
for(int i=0; i<10; i++){
numInput = input.nextInt();
if (numInput > largestValue){
largestValue = numInput;
}else if (numInput < smallestValue ){
smallestValue = numInput;
}
}
System.out.println( "Smallest is " + smallestValue );
System.out.println("Largest is " + largestValue);
Related
The purpose for the code is to prompt the user for 10 integers and then display the largest and smallest integer. I was able to ask the user for the 10 integers and display the largest number; however, the smallest number isn't shown. I believe the issue is with me setting smallest to 0.
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
int counter = 1;
int largest = 0;
int smallest = 0;
int number = 0;
Scanner input= new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else {
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}
Initialize your values like this so we guarantee that we start with the smallest/largest possible reference for our numbers to compare against to:
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int number;
int old = Integer.MIN_VALUE;
...and then some tweaks have to be made:
Change the way you check for dupe numbers (use and old variable).
Check if every new number is smaller than smallest number always (so, in the first iteration we assign the first value to smallest and largest)
Like this:
number = input.nextInt();
if (old != number) {
old = number;
if (number > largest) {
largest = number;
}
if(number < smallest) {
smallest = number;
}
/* consider moving next line here (this will guarantee to go to the next
iteration only if the numbers are different, and get in the final messages,
valid values for `smallest` and `largest` */
// counter = counter + 1;
} else {
System.out.print("Number isn't distinct");
}
Just make > into >= and < into `<=
Since 0 < 0 evaluates to false, your code block does not run. Thus the correction.
Variable smallest is always 0 so the program never go into this block else if(number < smallest)
You should add this code before if(number < smallest)
if(smallest == 0) {
smallest = number;
}
Also your code doesn't catch the distinct numbers. To find the distinct number you should define a list List<Integer> numbers = null; at the start of the program.
Then you can check if the input is entered or not in the while loop like this:
if(numbers.contains(number))
System.out.print("Number isn't distinct");
else
numbers.add(number);
Sets the largest and smallert variables with the user's first input and then compare
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner input= new Scanner(System.in);
int number = input.nextInt();
int counter = 1;
int largest = number;
int smallest = number;
while (counter < 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}
Trying to make a program that uses a partially filled array. The beginning of the code deals with getting user input for the array size and getting them to enter a value to be placed in the array. Then I want the values to be sorted as they are entered.
public static void main(String[] args)
{
int userInput;
int[] userArray;
int numElements;
int index;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of values in array (5 to 10): ");
userInput = keyboard.nextInt();
while (userInput < 5 || userInput > 10)
{
System.out.print("Enter number of values in array (5 to 10): ");
userInput = keyboard.nextInt();
}
System.out.println(); //Space, for neatness
userArray = new int[userInput];
for (int item: userArray)
System.out.print(item + " ");
System.out.print("\nEnter an integer value: ");
userInput = keyboard.nextInt();
int numElements = 0;
int index = 0;
if (numElements == userArray.length - 1)
System.out.println("The array is full.");
else
{
while (index < numElements && userArray[index] < userInput)
{
if (userArray[index] != 0) //Shift the array to the right, and add value at the current index as to not overwrite values.
{
for (int i = numElements; i > index; i--)
userArray[i] = userArray[i - 1];
userArray[index] = userInput;
}
userArray[index] = userInput;
index++;
numElements++;
System.out.print("Updated array: ");
for (int item: userArray)
System.out.print(item + " ");
System.out.println("\nEnter an integer value: ");
userInput = keyboard.nextInt();
}
}
}
Having trouble with my output. After I enter a value, the program terminates. For example (I print the empty array on purpose):
Enter number of values in array (5 to 10): 5
0 0 0 0 0
Enter an integer value: 5
Sorry for the lack of comments.
This part of your statement is always FALSE!
index < numElements
index and numElements are both 0 initially. Thus your while loop just skips and is done.
try replacing the last part of your code by this :
int numElements = 0;
while (numElements < userArray.length ) {
System.out.print("\nEnter an integer value: ");
userInput = keyboard.nextInt();
//insert into the first column
userArray[0] = userInput;
// order the table
for (int i=0 ;i<=(userArray.length-2);i++)
for (int j=(userArray.length-1);i < j;j--)
if (userArray[j] < userArray[j-1])
{
int x=userArray[j-1];
userArray[j-1]=userArray[j];
userArray[j]=x;
}
numElements++;
}
System.out.print("Updated array: ");
for (int item: userArray)
System.out.print(item + " ");
System.out.println("\nEnter an integer value: ");
userInput = keyboard.nextInt();
System.out.println("The array is full.");
I have encountered some problems with the calculating of largest and smallest number... If the first number I entered is a larger number than the 2nd number input, it will not record the 1st number into the largest...
Take a look at the output, it will help elaborate better..
Calculation Error.. &
1st input problem..
Codes below!
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
} else {
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
You could build an IntStream if you are using Java 8, and extract those numbers automatically using IntSummaryStatistics. You can find the official documentation from Oracle here.
Here is the code to achieve that:
List<Integer> input = new ArrayList<>();
while (true) { // LOOP till user enter "-1"
number = kb.nextInt();
// Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
input.add(number);
}
}
IntSummaryStatistics z = input.stream() // gives Stream<Integer>
.mapToInt(Integer::intValue) // gives IntStream
.summaryStatistics(); // gives you the IntSummaryStatistics
System.out.println(z);
If you input 8 3 7 the output will be:
IntSummaryStatistics{count=3, sum=18, min=3, average=6.000000, max=8}
I hope it helps!
Do it like this:
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
}
//REMOVED ELSE ADDED another IF
if (number > largest){
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
The problem is your if statement, as the logic is flawed. If the input number is smaller than smallest, then you update the smallest number. So far all is correct. The problem occurs, because you update largest in the else part. This means, if a number is not the smallest, largest is overwritten. But if the number is greater than the smallest, it is not automatically the largest. The right way to do this, is to check if the number is larger than the largest in a new if statement and update largest only in this case.
So I have a program I wrote that finds the max and min value of a five number set. It works for the most part but when I enter a set of numbers like {5,6,7,8,9} then it outputs 9 as the max, but outputs 0 for the min. Any thoughts or suggestions.
import java.util.Scanner;
public class MinMax {
public static void main (String [] args) {
#SuppressWarnings("resource")
Scanner in = new Scanner (System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i = 0;
double max = 0.0;
double min = 0.0;
System.out.println("Enter five numbers.");
System.out.println();
while (i < NUM_ELEMENTS) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
i++;
System.out.println();
}
for (i = 0; i < userVals.length; i++) {
if (userVals[i] > max) {
max = userVals[i];
}
else if (userVals[i] < min) {
min = userVals[i];
}
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
}
}
Default your min to a number out of range (like Double.MAX_VALUE), and max to Double.MIN_VALUE. You might also simplify your code by removing the second loop; you can perform the logic in one loop and you might use Math.max(double, double) and Math.min(double, double). Something like,
Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
System.out.println("Enter five numbers.");
System.out.println();
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < NUM_ELEMENTS; i++) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
min = Math.min(min, userVals[i]);
max = Math.max(max, userVals[i]);
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
Intialize your min variable to non-zero max value. Means max value that you can have in your input from console.
I'm currently writing a program where the user must input 10 numbers and then the output will be the highest number and the lowest number. There is something wrong in my code but couldn't find it.
int highest=0, lowest=0, num=0;
Scanner scan = new Scanner(System.in);
for (int i=0; i<10; i++) {
System.out.print("Enter a number:");
num = scan.nextInt();
}
if (num > highest) {
highest = num;
}
else if(num < lowest) {
lowest = num;
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
Initialise your values differently:
int highest = Integer.MIN_VALUE;
int lowest = Integer.MAX_VALUE;
If you initialise them both to zero, you will never have a "highest" value below zero, or a "lowest" value above zero
You should put your two if conditions in the for loop else you will only compare the last number. And lowest shouldn't be set to 0 but to Integer.MAX_VALUE
You have some issues with your initialization and your logic:
int highest=Math.MIN_VALUE;
int lowest=Math.MAX_VALUE;
int num=0;
Scanner scan = new Scanner(System.in);
for(int i=0; i<10; i++){
System.out.print("Enter a number:");
num = scan.nextInt();
if (num > highest){
highest = num;
}
if(num < lowest){
lowest = num;
}
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
You should also use 2 if conditions rather than an else if. If you have only one number, chances are that you will end up with something similar to highest being equal to some digit you entered while lowest will still be equal to Math.MAX_VALUE. This can cause confusion.
You are implicitly assuming that lowest and largest are 0, that might now be the case,
try this code snippet..
class Main{
public static void main(String args[]){
int highest=0, lowest=0, num=0;
Scanner scan = new Scanner(System.in);
highest = lowest = scan.nextInt();
for(int i=1; i<10; i++){
System.out.print("Enter a number:");
num = scan.nextInt();
if (num > highest){
highest = num;
}
if(num < lowest){
lowest = num;
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}
}
}