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.
Related
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
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.
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.
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);
I have an assignment to find the minimum, maximum, and average of numbers that a user inputs. Basically, they type in positive integers, seperated by a space and Java scrolls through them and adds them up. I'm able to find the sum, the average, and the largest integers, however, I am unable to find the smallest. I thought the best way to figure this out would be to set the variable representing the smallest int equal to the variable representing the largest int outside of the loop. Then, within the loop, do something like this:
if(getInt < min)
{
min = getInt;
}
Where getInt is the user-inputted value and min is the minimum integer value. Every time I run this, though, min returns as 0.
Here is my full code:
import java.util.Scanner;
public class exc5
{
public static void main (String[] args)
{
System.out.println("Write a list of nonnegative integers, each seperated by a space. To signal the end of the list, write a negative integer. The negative integer will not be counted");
Scanner keyboard = new Scanner (System.in);
keyboard.useDelimiter(" |\n");
int count = 0;
int sum = 0;
int max = 0;
int min = max;
double average = 0;
boolean notNull = true;
while(notNull == true)
{
int getInt = keyboard.nextInt();
if(getInt < 0)
{
notNull = false;
}
else
{
if(getInt > max)
{
max = getInt;
}
if(getInt < min)
{
min = getInt;
}
sum += getInt;
count++;
average = (sum)/(count);
}
}
System.out.println("Sum = " + sum);
System.out.println("Average = " + average);
System.out.println("Max = " + max);
System.out.println("Minimum = " + min);
}
}
Any help is appreciated!
You should initially set min to Integer.MAX_VALUE, and max to Integer.MIN_VALUE.
You need to start with a large min, not 0 (only negative numbers are less then 0). Try this:
int min = Integer.MAX_VALUE;
This is a fairly standard pattern. Also, to be "correct", your code should also include:
int max = Integer.MIN_VALUE;
Then the full range of integer input, positive and negative, is handled.
Edit:
Another, more "classic" approach would be to use an object reference, rather than a primitive (which always has a value), so the initial state can be easily distinguished as null. In this case, using Integer, rather than int for the values would allow testing for null. If I were a university professor marking such work, I would rather see the object approach - using min/max values for primitives will work, but it's a bit of a "trick".
The code wold look like this:
Integer min;
while (...) {
if (min == null || getInt < min) {
min = getInt;
}
}
And similar for max.
This:
int max = 0;
int min = max;
initializes min to zero. (After all, max hasn't become the largest integer yet.) So this:
if(getInt < min)
will never be true. Try changing this:
int min = max;
to this:
int min = Integer.MAX_VALUE; // largest possible Java `int`
That's because you're assigning min = 0, so obviously unless you input a number lower than 0, the minimum is 0. You should initialize min to Integer.MAX_VALUE
int min = Integer.MAX_VALUE;
(
or also:
int min = 0xFFFFFFFF;
Just for hacking around :P. Use the first one! :)
)
You are setting min to zero, so (since the inputs are positive) none of the inputs are less than min.
The normal way to do this is to set the initial value of max to Integer.MIN_VALUE, and the initial value of min to Integer.MAX_VALUE.
This ensures that any input value will affect at least one of min and max - usually both!
You initialize min with 0. Try to initialize with Integer.MAX_VALUE, i.e. it would be best to do:
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
Otherwise, your check:
if(getInt < 0)
will break out of the loop and you will never go over 0.
you have min set as 0 to start with so getInt will never be less. You should set min at the beginning of the loop and that will solve your issue.
Fully working and "cleaned" version of your program:
import java.util.Scanner;
public class exc5
{
public static void main ( String [] args )
{
Scanner keyboard = new Scanner( System.in );
int count = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double average = 0;
boolean notNull = true;
while ( notNull == true )
{
int getInt = keyboard.nextInt();
if ( getInt < 0 )
notNull = false;
else
{
if ( getInt > max )
max = getInt;
if ( getInt <= min )
min = getInt;
sum += getInt;
count++;
}
}
average = ( sum ) / ( count );
System.out.println( "Sum = " + sum );
System.out.println( "Average = " + average );
System.out.println( "Max = " + max );
System.out.println( "Minimum = " + min );
}
}