Smallest and Second Smallest of a number list - java

Problem 2
Write your program in the file TwoSmall.java.
Input a set of positive integers, ending with -1 as a sentinel. Print the smallest and second smallest of these numbers in that order.
You may assume there are always at least two numbers before the -1; you do NOT have to check for this being true.
public class TwoSmall{
public static void main(String [] args){
int min;
int secondMin;
int sentinel = -1;
System.out.println("Enter atleast two numbers");
int input = IO.readInt();
min = input;
secondMin = input;
do{
if(input < min){
secondMin = min;
min = input;
}
else if (input < secondMin) {
secondMin = input;
}
input = IO.readInt();
} while(input!=sentinel);
System.out.println(min);
System.out.println(secondMin);
}
}
This is not working? Could someone tell me what is wrong with this program?

It's because you set both min and secondMin equal to the first entered value. Unless the numbers entered are less than that value, you'll have an issue. Try reading in both those numbers separately.
min = IO.readInt();
secondMin = IO.readInt();
Also, rethink your logic. You might be getting a backwards result. A way to work yourself around this problem is to read the first two integers, then assign them to min and secondMin accordingly. Otherwise, if the user enters 4,3,2 -- the result will say that 3 is the lowest and that 2 is the second lowest - which is incorrect.
Another option, as mentioned by #vandale is to initialize both of them to INTEGER.MAX_VALUE. If you do this, you eliminate the need to read in initial values for min and secondMin.

Related

The Largest/Smallest Outputs do not showcase the right values

Should receive an output of the largest/smallest numbers within the inputs, what seems to be the problem? I have tried looking it up online, the source code appears to be the same. Thank you for your assistance.
Source code:
package counting.largest.smallest;
import java.util.Scanner;
public class CountingLargestSmallest {
public static void main(String[] args) {
Scanner TheN = new Scanner(System.in);
int counter = 0;
int number;
int smallest = Integer.MIN_VALUE;
int largest = Integer.MAX_VALUE;
while (counter < 10) {
System.out.print("Integer=");
number = TheN.nextInt();
counter++;
if (number < smallest) {
number = smallest;
} else if (number > largest) {
number = largest;
}
}
System.out.println("\nSmallest=" + smallest);
System.out.println("Largest=" + largest);
}
}
Output:
Integer=1
Integer=2
Integer=3
Integer=4
Integer=5
Integer=6
Integer=7
Integer=8
Integer=9
Integer=10
Smallest=-2147483648
Largest=2147483647
there were 3 bugs:
1.
int smallest=Integer.MIN_VALUE;
int largest=Integer.MAX_VALUE;
number=smallest;
number=largest;
Using else if
1: When you want to find a min number keep it Integer.MAX_VALUE and when you want to find max keep it has Integer.MIN_VALUE.
Why for min we Initialize Integer.MAX_VALUE and for max we Initialize Integer.MIN_VALUE?
Say you want to multiple n numbers from the user. So we will declare and initialize mul variable to 1. cause we know any number multiple by 1 will give us the same number.
Whereas if we initialize mul with 0 it will give us 0 only.
So we say 1 for multiplication is identity.
Similarly, for finding Minimum number we use an identity that is Integer.MAX_VALUE.
So that number that less then Integer.MAX_VALUE are saved in Samllest variable.
int smallest=Integer.MAX_VALUE;
Similarly for max we initialize it with Integer.MIN_VALUE SO that number that are greater then Integer.MIN_VALUE are stored in largest variable.
int largest=Integer.MIN_VALUE;
2: You are assigning number variable the value of smallest and largest it should be like smallest=number and largest=number
when you write x=0 it says x is 0 that means x is changed, Similarly when you write number=smallest its number = Integer.MAX_VALUE and smallest is not changing at all.
So you should write like smallest = number, It means smallest is the number and smallest is changing every time condition satisfies.
3: When you write
if(condition){
}else if(conditon){
}
else if is only excuted when first if statement if false and if first condition is true second if is never executed.
if we have descending number then second if will never be excuted which would result in having Integer.MIN_VALUE in largest variable.
And here you want to check for both min and max so we should have indepent if statement for each
if(condition){
}
if(condition){
}
Code:
Scanner TheN= new Scanner(System.in);
int counter=0;
int number;
// changed
int smallest=Integer.MAX_VALUE;
int largest=Integer.MIN_VALUE;
while(counter<10){
System.out.print("Integer=");
number=TheN.nextInt();
counter++;
if(number<smallest){
// changed
smallest= number;
}
if(number>largest){
// changed
largest=number;
}
}
System.out.println("\nSmallest="+smallest);
System.out.println("Largest="+largest);
Output:
Integer=1
Integer=2
Integer=2
Integer=4
Integer=3
Integer=6
Integer=7
Integer=8
Integer=9
Integer=10
Smallest=1
Largest=10

Java program infinite loop in sum of even integers

I am creating a program that prints the sum of the even numbers from a range of 0 to the number that the user entered. For example, if the user entered the number 20, the program would calculate the sum of all of the even numbers between 0 and 20.
When I tested the program out with the number 10, it worked. But I tried using a different number, 35, and it was just stuck in an infinite loop. I would appreciate any and all help. The code will be posted below:
(Edit) Thanks for the feedback everyone! After talking with a friend, we realized that the solution is actually pretty simple. We were just making it complicated. Still, thanks for all of the suggestions.
//**************************************************************
// Prints the sum of the even numbers within a range of 0
// and the integer that the user enters.
//
// #me
// #version_1.0_11.7.17
//**************************************************************
import java.util.Scanner;
public class EvenNumbersSum
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int user_num = 2; // variable that stores the user's number
int sum; // stores the sum of the needed values
System.out.print("Enter an integer greater than or equal to, 2: "); // prompt user for input
user_num = input.nextInt();
// checks to see if the value entered is valid or not.
while (user_num < 2)
{
System.out.println("Invalid entry. Must enter an integer greater than or equal to, 2.\n");
System.out.print("Enter an integer greater than or equal to, 2: ");
user_num = input.nextInt();
}
// starts adding the values
for (sum = 0; sum <= user_num;)
{
if (user_num % 2 == 0) // checks if the number is even
sum+=user_num; // add the number to sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
System.out.println(); // extra line for cleanliness
System.out.printf("The sum of the even numbers between 0 and %d is %d.", user_num, sum); // prints the result
}
}
Why are you writing loop for this, there are efficient way to do it.
Sum of numbers between 1-N = (N(N+1))/2
Sum of even numbers between 1-N = (N(N+2))/4
where N = user given input number till which you would like to add even numbers
NOTE: you can add validation on input number that it’s even by (n%2 == 0) and return error if it’s not
The variable you have used in condition (i.e. sum & user_num) no one changes in case of odd number and your code stuck in never-ending loop.
You should use counter variable ( e.g. i from 1 to user_num) and use that number in the condition. Example:
// starts adding the values
sum = 0;
for (int i = 0; i <= user_num; i++)
{
if (i % 2 == 0) // checks if the number is even
sum+=i; // add the number to sum
}
Your for loop should be like this.
int total_sum = 0;
for (int sum = 0; sum <= user_num; sum++)
{
if (sum % 2 == 0) // checks if the number is even
total_sum+=sum; // add the number to total sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
// note print total sum
System.out.println(totalsum);
your initial program just kept on checking entered number is even or odd.
And the entered number to sum.
So sum was always double of the entered number is even.
If entered number is odd it would go to infinite loop as entered_num(odd) % 2 == 0 always false and execute else statement.

How to get the max and min values of a number

I tried to make a program that gets the max and min value of the numbers in which the user entered.
Here is the code:
Scanner in = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int value;
boolean isInt;
System.out.print("Enter an integer: ");
isInt = in.hasNextInt();
if (isInt == true){
value = in.nextInt();
}
for (int i = 0; isInt == true; i = i){
System.out.print("Enter an integer: ");
isInt = in.hasNextInt();
if (isInt == true){
value = in.nextInt();
}
}
System.out.println(min);
System.out.println(max);
And the output is:
2147483647
-2147483648
What is the error in the code?
The definition for Min and Max of integer is not to get the Min and MAX from input.
They are constant value.
MAX_VALUE
A constant holding the maximum value an int can have, 231-1.
MIN_VALUE
A constant holding the minimum value an int can have, -231.
Once you initialize them, you never change max or min anywhere.
First thing: what you have is not pseudo code. It's just bad actual code.
To answer your immediate question, you need to set the values of min and max to something other than their initial values. They will not magically update themselves.
There are a couple of additional things you are doing that should probably be fixed:
Since isInt is boolean, you do not need to compare it to true to get its boolean value: if(isInt) is fine.
Every time you call nextInt() on the Scanner, you invalidate the previous result of hasNextInt(). In other words, once you get the next int, you don't know that there is going to be another one in the input until you call hasNextInt() again. Your for loop makes this assumption.
Here is a version of the code that not only fixes the three issues noted above, but is also indened correctly:
Scanner in = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int value;
System.out.print("Enter an integer: ");
while(in.hasNextInt())
{
System.out.print("Enter an integer: ");
value = in.nextInt();
if(value < min)
{
min = value;
}
if(value > max)
{
max = value;
}
}
System.out.println(min);
System.out.println(max);
Note that I do not use an else clause when comparing value against the current min and max. This will ensure that min and max are correctly set to the first input even if there is only one number in the sequence.
Nowhere in your code are you changing the values of max or min. If you want to print the min and max of the inputted numbers you could run a couple comparisons for maximum and minimum. The easiest way would look like this, inserted after you take in the value for the integer:
if(value > max)
max = value;
if(value < min)
min = value;
You should probably remove these lines as well as they're no longer needed:
System.out.print("Enter an integer: ");
isInt = in.hasNextInt();
if (isInt == true)
{
value = in.nextInt();
}
Additionally both isInt and value will have to be initialized to a value.

Java will not add first integer when computing average

I am new to Java, so I apologize if I am simply overlooking something simple. I wrote this code to make a few simple calculations, but when I run it, Java does not seem to be adding my first integer that is input when calculating the average. Everything else seems to be fine, so I would appreciate any help. Thanks.
import java.util.Scanner;
public class IntegerCalc {
public static void main(String[] args){
System.out.println("Enter a list of non-negative integers.");
System.out.println("Enter a negative number to indicate the end of your input.");
Scanner keyboard = new Scanner(System.in);
int min = keyboard.nextInt();
int max = min;
double average = 0;
double numberOfInt= 1;
int next = keyboard.nextInt();
double total = 0;
while (next > 0){
if (next > max)
max = next;
else if (next < min)
min = next;
total = total + next;
numberOfInt++;
next = keyboard.nextInt();
}
average = total/numberOfInt;
System.out.println("The largest integer is " + max);
System.out.println("The smallest integer is " + min);
System.out.println("The average is " + average);
}
}
It looks like your code does sum all the input numbers, but your numberOfInt is off by one.
You should initialize it to
double numberOfInt= 0;
instead of
double numberOfInt= 1;
You only want to increment numberOfInt when you add the current value of next to the total, so the first time you add next to total, numberOfInt should become 1.
What I can see is that inside while loop you have this condition:
if (next > max)
max = next;
else if (next < min)
min = next;
Your first value never goes to total.Your first value will count towards average is only when value of next is equal to first value.To solve this problem you can initialize total with max or min(since they are equal initially):
double total = (double) max;
your int numberOfInt should not be initialized at value 1. Since you increment it by 1 with each iteration of your loop, it's value is off by one. Instead, initialize it at value 0.

Do-while statements beginner java max-min prompt

Hey guys I new to Java and on do-while statements, the question asks me to create a prompt that asks for a max and a min value, then it asks for another value between my max and min values. "The user should be continually be prompted until a number within the range is entered. Im having a hard time wrapping my head around using a do-while statement so some help would be nice thanks! Also try to keep it simple!
package Chapter6Java;
import java.util.Scanner;
public class Chapter6Prompter {
public static void main(String [] args){
int max, min, between;
Scanner input = new Scanner(System.in);
System.out.print("Enter a min value: ");
min = input.nextInt();
System.out.print("Enter a max value: ");
max = input.nextInt();
do {
System.out.print("Enter a value between your min and max values:");
between = input.nextInt();
} while (between != max && between != min);
}
}
Modify your condition in the while as:
while (between >= max || between <= min);
Since you are checking that between is in range you should check if its greater than or equal to minimum value and less than or equal to maximum value.
You want to repeat the loop if the number rentered in not in range
so condition will be - while (between > max || between < min);

Categories