Find two smallest numbers using java? - java

I need help to compute the two smallest numbers in java?... plzz help.. Usage for arraylist and arrays are not allowed.. The user shall be asked for a terminating value first and will continue to provide inputs and once the user enters the same terminating value the program should output the two smallest numbers from the inputs excluding the terminating value..
Additional Details Could show me how to do it... The sentinel value is the value if entered again by the user shall stop the program and output the two smallest numbers.
package hw4;
public class s1 {
public static void main(String[] args) {
int input;
int min;
int min2;
System.out.print("Enter a value to act as sentinel:");
int sentinel = IO.readInt();
System.out.println("Enter numbers");
input = IO.readInt();
do {
min = input;
min2 = input;
if (input < min) {
min = input;
}
input = IO.readInt();
} while (input != sentinel);
// Return the results
System.out.println("The smallest Number is: " + min);
System.out.println("The second smallest Number is: " + min2);
}
}

I'm assuming this is homework, based on the nature of the question. So ...
Hint: if x was the smallest and y is now the smallest, then x is now the second smallest.
Hint 2: make sure your program works when the smallest and second smallest values are equal.

When you find a new min, save the previous minimum in your min2 variable and then reassign min to the current input.
if (input < min) {
min2 = min
min = input;
}

This would work if you needed to find only the smallest number, but you need to find the two smallest numbers, so the if should go like that:
if(input < min) {
min2 = min;
min = input;
}
else if (input < min2) {
min2 = input;
}
And I know min & min2 need a value at start, so instead of changing their value to input every time, just do that at the fist time. So also get this part out of the do:
min = input;
min2 = input;

Related

Getting 0 for minimum value but the maximum value is okay

I am trying to input an array using a scanner. That part is already done. Now, I am tasked to get the maximum and minimum numbers from my input. I was able to get the maximum but with the minimum, it is returning 0.
Is there a misplacement of syntax perhaps?
import java.util.Scanner;
public class App {
public static void main(String[] args) {
int in;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
in=sc.nextInt();
int array[] = new int[in];
int min = array[0];
int max = array[0];
for (int i=0; i < in; i++){
System.out.print("Input number "+(i+1)+" :");
array[i]=sc.nextInt();
if(array[i]>max){
max=array[i];
}
else if (array[i]<min){
min=array[i];
}
}
sc.close();
System.out.print(" The inputed array is ");
for (int i=0; i < in; i++){
System.out.print(array[i]+" ");
}
System.out.println("\n --------------------");
System.out.println("The highest number is: "+max);
System.out.println("The lowest number is: "+ min);
}
}
(also if you can, can y'all tell me how to get the index of the minimun and maximum value and print it?)
I tried different if and else if methods. I also tried nesting but I am getting the same outcome.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
int in;
List<Integer> elements = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
in=sc.nextInt();
for (int i=0; i < in; i++){
System.out.print("Input number "+(i+1)+" :");
elements.add(sc.nextInt());
}
sc.close();
List<Integer> unsorted = new ArrayList<>(elements);
Collections.sort(elements);
int max = elements.get(elements.size()-1);
int min = elements.get(0);
System.out.println("\n --------------------");
System.out.println("The highest number is: "+max);
System.out.println("The lowest number is: "+ min);
System.out.println("Index of Min Value is : "+unsorted.indexOf(min));
System.out.println("Index of Max Value is : "+unsorted.indexOf(max));
}
}
When you declare an initialize your int array[]:
int array[] = new int[in];
you essentially are filling each array element with 0 by default. Then, when you declare and initialize the min and max variables with array[0] it would be the same as declaring:
int min = 0;
int max = 0;
The max variable is at a relatively low value which is good unless the User enters all signed (negative) integer values to make up the array elements in which case none of those entry values will ever max over 0 which means at the end, max will be 0 which is also wrong.
The same theory applies to the min variable. Since the min variable already holds a low value of 0 (initialized as such), the only way an element value within the array[] Array will be lower is if the array actually contained a signed (negative) value. If it doesn't the the already held value in min will remain to be the lowest value...which as you know will be in most cases wrong.
The thing to do in this particular use-case would be to initialize the min variable with a value which would be the largest a int data type can hold:
int min = Integer.MAX_VALUE;
You would be pretty much guaranteed that a value within the int[] array will never exceed Integer.MAX_VALUE and that if there is a element within the array that is lower, min will end up getting updated to that value.
The same should be applied to the initialization of the max variable except with the lowest possible int data type value:
int max = Integer.MIN_VALUE;
I think at this point you can understand why. ;)
So, all in all, simply change:
int min = array[0];
int max = array[0];
to this instead:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
and all should be fine.
On A Side:
In a real world application where a User is expected to fill in values for an Array, there is no way of knowing what the User (like your instructor) may be entering to fill the elements of that array unless you code specifically to ensure a particular value range. By doing what is described above eliminates any worry of that unless the User supplies a value greater than what an int data type can accept in which case an exception would occur and the application will crash.
You are initializing min even before taking inputs. That's why the min value is always 0 because the default initial value of int array is 0. So, the else if (array[i]<min) condition is never met because no non-negative integer can be smaller than 0.
You can try adding this in your for loop AFTER you take inputs:
if(i==0){
min = array[0];
max = array[0];
}
You can also use type Integer (instead of int), as they can be initialized by null
Integer max = null;
Integer min = null;
In your loop:
if(max == null || max < array[i]) {
max = array[i];
}
if(min == null || min > array[i]) {
min = array[i];
}

I need my code to find the average of all the scores and print it out in a dialog box

I am having problems trying to get the average of the scores. Could you please help me fix this code.
import javax.swing.*;
public class ProgrammingExercise6b{
public static void main(String[] args){
String input = "";
int score = 0;
int count = 0;
int sum = 0;
do {
count++;
input = JOptionPane.showInputDialog("Please enter the grades:");
score = Integer.parseInt(input);
if (score == -1) {
sum += score;
JOptionPane.showMessageDialog(null, "The average is: " + (score / count));
break;
} else {
continue;
}
} while (true);
} //main
}
I need help to understand how to add up all the numbers and divide them by the number of numbers to get the average.
move sum += score; and count++ in else part, before continue; line. Also use sum in calculation final result. Your updated code should look like below
String input;
int score ;
int count = 0;
int sum = 0;
do {
input = JOptionPane.showInputDialog("Please enter the grades:");
score = Integer.parseInt(input);
if (score == -1) {
JOptionPane.showMessageDialog(null, "The average is: " + (sum / count));
break;
} else {
sum += score;
count++;
continue;
}
} while (true);
for the scores you should store them in an ArrayList List<Integer> scoresList= new ArrayList<Integer>();
To add to the arrayList you use
scoresList.add(yourScore);
have a seperate integer "scoresSum" which is the sum of your scores.
To get the sum you iterate through the list. something like this
for(int score: scoresList)
{
scoresSum += score;
}
finally have a variable average which equals the average
int average = scoresSum/scoresList.size();
also since you want to check the score isn't -1. add the score to the ArrayList after you check that the value is not equal -1
This looks a lot like a homework assignment, I would first and foremost recommend brushing up on your math. You need to understand how an average is calculated before you can write any code.
For example in order to calculate the Average it will be the sum divided by the total count and logically you should only increment count when the sum is updated (score is added).
Hope that points you in the right direction. You must understand how to solve the problem before you correctly code a solution.

Find a maximum and minimum value using for loop

I am trying to take 10 integers from the user's input and find the minimum and maximum using for loop. But my final print statement just prints the list of numbers entered. I'm lost.
public static void main(String[]args) {
Scanner scan=new Scanner(System.in);
double a = 0;
double max = 0;
double min = 0;
System.out.print("Enter ten floating points: \n");
for(a=0; a <10; a++) {
a=scan.nextDouble();
if(a == 0) {
min=a;
max=a;
}
else if(a < min) {
min=a;
}
else if (a > max){
max=a;
}
}
System.out.println("Minimum value: " +min);
System.out.println("Maximum value: " +max);
}
Issue is in your for loop change it to
for (int x = 0; x < 10; x++) {
there is another issue, you need to change
if(a == 0){
To
if (x == 0) {
Try this
Scanner scan=new Scanner(System.in);
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
for( int i=0; i<10 && scan.hasNextInt(); i++ ) {
int next = scan.nextInt();
maximum = Math.max( next, maximum);
minimum = Math.min( next, minimum);
}
System.out.println("Found maximum :"+maximum+", minimum:"+minimum);
scan.close();
First, we create the scanner.
Next, we set a value for your maximum - since integers can be negative, we can not use 0, but have to use the smallest possible integer.
Same for minimum.
In the for loop, we have to make sure that we terminate the loop after 10 iterations, or if the input stream does not have any more int's.
Next, we use the mathematical function max to find out which number is largest - the previously found maximum, or the next int from the Scanner.
And same for minimum.
Finally, remeber to close the Scanner, to avoid resource leakage.
First your code should not run correctly since you use the same variable a as the counter and as the variable to store user input. You should use two different variable.
Second declare your variable that store the input from user inside the loop, otherwise it may keep the value from the previous loop.
Third your if(a == 0) condition will reset min and max when the user enter the number 0. Which is not what you want.
Finally you should not initialize max/min like that. By defining min as 0, if the user enter only positive number the min will be 0 but the user never entered 0. You instead initialize them at the first entry from user.
This should look like this :
public static void main(String[]args) {
Scanner scan=new Scanner(System.in);
System.out.print("Enter ten floating points: \n");
double tmp = scan.nextDouble(); //read first number from user
double max = tmp; //intialize with the first input
double min = tmp;
for(int i=0; i <9; i++) { //from 0 to 8, 9 numbers since the first has already been read
double a = scan.nextDouble(); //at every loop read a number from the input
if(a < min) {
min=a;
}
//removed else since max and min are independant
if (a > max) {
max=a;
}
}
System.out.println("Minimum value: " +min);
System.out.println("Maximum value: " +max);
}

Removing all the zeros from an array using scanner

I needed an array that takes integers from a user until '0' is entered; then it prints average, max and min. I wrote an array with 700 elements and it breaks. When I input 0 everything works well. The problem is when I input 0 it takes 0 as an element. I solved that somehow so it can calculate the average correctly but it still takes some 0 from somewhere. For example, I input 8 and then 3 and then 0, and the output is the average is 4.000000, the biggest one is 5, the smallest one is 0, but the smallest one should be 3.
I guess it's because the remaining 697 elements are considered as 0.
I found a lot of answers for this problem but I want to solve it without copying the array or creating a new one. Is there anything that I can do to fix this without adding an array or another for loop or something? Like a line that means 'when the 0 is entered remove all remaining elements and don't use them for anything'?
import java.util.Scanner;
import java.util.stream.IntStream;
public class PlayingWithNumbers2 {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
int[] array = new int[700];
System.out.println("Enter numbers enter 0 to end");
int i;
int max = array[0];
int min = array[0];
int a = array[0];
for (i = 0; i < array.length; i++) {
a=input.nextInt();
if(a==0){
break;
}
array[i] = a;
if(array[i]>max)
max = array[i];
else if(array[i]<min)
min = array[i];
}
double sum = IntStream.of(array).sum();
double Ave = sum/i;
System.out.printf(" The Average is %f \n the biggest one is %d \n the smallest one is %d", Ave, max, min);`
}
}
The problem with the min/max is both are initialized to array[0] which means both are initialized to '0' and so the min check will always keep it at 0 as it is below anything you enter. You also need to remove the else condition. Try this
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
then inside the loop change the checks to be
if(array[i]>max)
max = array[i];
if(array[i]<min)
min = array[i];
You can use range():
double sum = IntStream.of(array).range(0, i).sum();
double Ave = sum/(i-1);
In this way, you'll be counting only numbers that are truly entered by the user and leave 'fake' 0 out of your sum.

Issue in displaying correct largest and smallest numbers

i'm very new to programming, and am attempting to create a program that will allow me to enter several integers and a separate one to quit, and upon quitting will return with the largest and smallest numbers. Everything works well except when displaying the largest and smallest numbers it only displays the quit integer, in this case -99. Here is my code, any help would be great.
import java.util.Scanner;
public class LargestSmallest
{
public static void main(String [] args)
{
//identifier declarations
int number;
int numberend = -99;
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
//create a Scanner object to read from the keyboard & input
Scanner keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//display prompts and get input
System.out.println("Enter an integer, or -99 to quit:");
number = keyboard.nextInt();
if (number == -99){
System.out.println("You did not enter any numbers.");
}else{
//loop
while ((number = input.nextInt()) != -99) {
System.out.println("Enter an integer, or -99 to quit:");
}
}
//largest & smallest
{
if (number > largest)
largest = number;
if (number < smallest)
smallest = number;
System.out.println("Largest:" + largest);
System.out.println("Smallest:" + smallest);
}
}
}
Your code is not keeping track of the current largest and smallest numbers as they are entered in. Please see the modifications below:-
public static void main(String[] args) {
//identifier declarations
int number;
int numberend = -99;
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
//create a Scanner object to read from input
Scanner input = new Scanner(System.in);
//display prompts and get input
System.out.println("Enter an integer, or -99 to quit:");
while ((number = input.nextInt()) != numberend) {
System.out.println("Enter an integer, or -99 to quit:");
if (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
}
//largest & smallest
System.out.println("Largest:" + largest);
System.out.println("Smallest:" + smallest);
}
When inside your loop, you only save the last entered number in number. To exit the loop you must enter -99 which also makes that the only number you have saved. Therefore, in your code, number will always be -99. -99 is both larger than your largest (INTEGER.MIN_VALUE) and smaller than your smallest (INTEGER.MAX_VALUE) so this is why -99 is printed.
To solve this, you can use two variables to save the current largest and current smallest number.
You can also solve this by using a list instead. Save all the inputs in the loop in some kind of list like ArrayList. Then, when the user has entered -99, you must examine the list to find the largest and smallest number. This is not an optimal solution, but may help you understand what is happening.

Categories

Resources