Issue in displaying correct largest and smallest numbers - java

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.

Related

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);
}

Reading in multiple integers from the scanner and assigning each integer to a different variable?

I have to read in integers and the scanner has to continue to scan them in until 0 is entered. Then all of those numbers have to be saved to different variables. Then the variables have to be compared and the following has to occur:
Find the smallest integer
Find how many integers are even
Find the sum of the negative integers
I have this so far:
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter integers");
do
{
}
while (in.nextInt() !=0);
}
I am lost on what to do next.
There are quite a few issues here, which would be solved if you read the docs for Scanner. Please don't expect people here to simply write your code for you. I'm doing this as an exception.
Your goal is to get the smallest integer, the number of even integers, and the sum of the negative integers. The code will stop running once the number 0 is entered.
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter integers");
int min = Integer.MAX_VALUE; // init to max possible
int numEven = 0;
int sumNeg = 0;
while (true) {
int val = in.nextInt();
if(val == 0) // stop if 0 is entered
break;
// check small
min = Math.min(val, min);
// check even
if(val % 2 == 0)
evenNum++;
// sum negatives
if(val < 0)
sumNeg += val;
}
}

finding smallest and second smallest number

This program is supposed to find the smallest and the second smallest number among x numbers.
The program finds the smallest number every time, but I have problems replacing the second smallest number from the keyboard.
System.out.println("How many numbers?");
int total = keyboard.nextInt();
System.out.println("What is the first number");
int small = keyboard.nextInt();
System.out.println("whats the second number");
int nest = keyboard.nextInt();
// Assigning the first two numbers to smallest and second largest
for (int i =2;i<total;i++) {
System.out.println("whats the next number?");
int number = keyboard.nextInt();
if (number < small) {
small = number;
} // this part works (I think)
if ((number > small) && (number < nest)) {
nest = number;
}//this part dont (I think)
}//end forloop
System.out.printf("The smallest numbers are %d and %d",small,nest);
You just have to get the order right. First, see if the number is smaller than the smallest number, and if so, replace it and move the old smallest number to the second smallest number. Else, if it is smaller than the second smallest number, replace that.
Here's the code that should be in the loop:
if (number < small) {
nest = small;
small = number;
} else if (number < nest) {
nest = number;
}
Add all the numbers to a LinkedList<Integer> then sort the List. The first two items in the List will be the smallest.
public class Sorter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<Integer> numbers = new LinkedList<Integer>();
System.out.println("How many numbers?");
int total = keyboard.nextInt();
System.out.println("What is the first number");
numbers.add( keyboard.nextInt());
System.out.println("whats the second number");
numbers.add( keyboard.nextInt());
// Assigning the first two numbers to smallest and second largest
for (int i =2;i<total;i++) {
System.out.println("whats the next number?");
numbers.add( keyboard.nextInt());
}//end forloop
Collections.sort(numbers);
System.out.printf("The smallest numbers are %d and %d",numbers.get(0),numbers.get(1));
}
}

I am creating a small program in java which asks for 5 integers to inputted by the user and put into an array

This is the code that I have attempted, I can get the 5 integers into the array but my problem is validating that input and giving an error message when it is not. If I put in the 5 integers and they are in the required range it works and when I input a number that is not in the required the range I get an error message which is what I want but if I enter a symbol or letter my program crashes.
import java.util.Scanner;
public class QuestionNr1 {
public static void main(String[] args) {
//Keyboard Initialization
Scanner scanner = new Scanner(System.in);
//Declare an array to hold 5 integers values
int list[] = new int[5];
int i = 0;
int sum = 0;
System.out.println("Please enter 5 numbers within the range 1 - 20, with 1 being the lowest and 20 being the highest.");
while (i < 5) {
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = scanner.nextInt();
if (value >= 0 && value <= 20) {
list[i] = value;
i++;
} else {
System.out.println("Invalid input, please enter a number with the required range of 1 - 20.");
}
}
for (int j = 0; j < list.length; j++) {
int value = list[j];
}
double average = 0;
for (int i1 = 0; i1 < list.length; i1++) {
sum = sum + list[i1];
}
System.out.print("The sum total of your five entered numbers = " + sum);
}
}
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = Integer.MIN_VALUE;
if (scanner.hasNextInt()) int value = scanner.nextInt();
else System.out.println("Please make sure the value you entered is an integer.");
You should check that the user inserts an int before assuming so (scanner.nextInt();).
You are using scanner.nextInt(); so it is expected that the text entered will be int and if you enter other then int it will throw exception
I would use scanner.nextLine() and then try to convert String into int with NumberFormatException check:
int value;
String input = scanner.nextLine();
try {
value = Integer.valueOf(input);
} catch (NumberFormatException ex) {
System.out.println("Number format exception");
continue;
}
if (value >= 0 && value <= 20)
...
If you are doing Q1 for C2 paper in DCU than its the Sum total you display at the end not the average. I was going to do add another While loop after the scanner.nextint() to test the input is a valid integer. The 3 validations would be is number an integer and is it in range and the number of integers to be entered to the array is 5. I am thinking very similar to you, its adding the extra check and where is goes in the sequence.

Find two smallest numbers using 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;

Categories

Resources