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);
}
Related
I am working on a coding project where I have to have a user input five specific float values. Then based on those values I have to to get a total, maximum, minimum and then apply interest. I am stuck right now on getting the minimum value from the array. I have been able to get the maximum value but when I print the minimum value I get 0.0. Any ideas?
import java.util.Scanner;
public class float_assignment {
public static void main(String[] args) {
float[] userNum = new float[5];
float total = 0;
float average = 0;
float maximum = userNum[0];
float minimum = userNum[0];
float interest = 0;
int i = 0;
Scanner scnr= new Scanner(System.in);
for (i = 0; i <= 4; ++i) {
System.out.println("Please enter a number with a single decimal value:");
userNum[i] = scnr.nextFloat();
}
for (i = 0; i < userNum.length; ++i) {
if (userNum[i] > maximum) {
maximum = userNum[i];
}
}
for (i = 0; i < userNum.length; ++i) {
if(userNum[i] < minimum) {
minimum = userNum[i];
}
}
total = userNum[0] + userNum[1] + userNum[2] + userNum [3] + userNum [4];
System.out.println("");
System.out.println("Total value is: " + total);
System.out.println("");
System.out.println("Maximum Vaule is: " + maximum);
System.out.println("");
System.out.println("Minimum Vaule is: " + minimum);
}
}
The problem is with this
float[] userNum = new float[5];
.. //some other declarations
float minimum = userNum[0];
When you create an array of type float, all the elements are initialized to 0.0 (and it is obvious that you are inputting only positive numbers greater than 0)
See : java: primitive arrays — are they initialized?
To overcome this, initialize minimum (and maybe maximum too) after inputting the numbers from the console.
for(i = 0; i<=4; ++i) {
System.out.println("Please enter a number with a single decimal value:");
userNum[i]= scnr.nextFloat();
}
minimum = maximum = userNum[0];
//Proceed to find max and min
Note that you don't need two loops to find min and max and can combine them into one.
for(i = 0; i < userNum.length; ++i ) {
if(userNum[i]> maximum) {
maximum = userNum[i];
}
if(userNum[i] < minimum) {
minimum = userNum[i];
}
}
The issue is in the initial value of minimum. It's currently set at 0.
if(userNum[i] < minimum)
Will therefore never be true (assuming positive values). So you need to set the value of minimum to maximum just before you start the loop. Either that or set it to the max value allowed by float.
Java 8 version :
OptionalDouble min = IntStream.range(0, userNum.length).mapToDouble(i -> userNum[i]).min();
float minimum= (float) min.getAsDouble();
This is because in your initialization-
float userNum[] = new float[5];
Array userNum is by default being initialized with all zeros and it look like
userNum=[0.0,0.0,0.0,0.0,0.0]
And hence maximum and minimum are also initialized with 0.0
You might be entering all the positive values in the input that is why your maximum is showing correct but minimum remains 0.0
To avoid this initialize maximum and minimum with the first value of the array inside the for loop after it has been taken from the user.
Add this if statement inside your for loop of array assignmet
if(i==0)
{
maximum=minimum=userNum[0];
}
Please note that by convention, it is advised to begin your class-name with a capital letter. :)
Here, the logic you have applied is wrong. To make it work properly, you need to add another for loop inside your existing one. Then the value of variable 'minimum' must be updated during each iteration of your outer for loop and finally, place your if-condition inside inner for loop. Check the updated code given below:
for(i = 0; i< userNum.length; ++i) {
minimum = userNum[0]; //updating value at each iteration.
for(i = 0; i < userNum.length; ++i) { //newly added loop.
if(userNum[i] < minimum) {
minimum = userNum[i];
}
}
}
I'm trying to find the minimum element in an array of size 25 elements are read by user and should stop when the user enters -1
import java.util.*;
public class LabSheet4{
public static void main (String[] args){
Scanner read = new Scanner (System.in);
double scores[] = new double[25];
int minIndex=0, i =0, sentinel=0;
do{
scores[i] = read.nextDouble();
if(scores[i]==-1)
sentinel=-1;
i++;}while(sentinel!=-1);
for(int k=0;k<scores.length;k++)
if(scores[minIndex] > scores[k] && scores[minIndex]>0)
minIndex = k;
lowestScore = scores[minIndex];}}
How do I exclude -1?
One way would be to not put the value in the list until after you know it isn't the sentinel.
Another would be to not increment the counter when you find you have added the sentinel. Note that this means you need a slightly bigger array.
One way is not to store it in the first place but another fix would be to ignore it when running on the array like this.
for(int k=0;k<scores.length;k++)
if(scores[minIndex] > scores[k] && scores[minIndex]>0 && scores[k] !=1)
One common idiom for this class of problems, is to use a while loop with an assignment and test. Something like,
double scores[] = new double[25];
int i = 0;
double score;
while ((score = read.nextDouble()) != -1) {
scores[i] = score;
i++;
}
Then you could start at 0 and iterate from 1 to i (because 0 is your initial value and i is the count of elements). Like,
int minIndex = 0;
for (int k = 1; k < i; k++) {
if (scores[minIndex] > scores[k]) {
minIndex = k;
}
}
double lowestScore = scores[minIndex];
Instead of
if(scores[i]==-1)
sentinel=-1;
use
if (scores[i]==-1 && i > 0) {
sentinel=-1;
scores[i] = scores[minIndex];
}
so you replace -1 with (so far) the lowest value - which is OK, isn't it?.
Do not store -1 in scores at all.
That way you won't have to exclude it later.
Most importantly,
it's not a functional value like the other values you store,
but a symbol with a special technical meaning in the way you process input.
As such, it doesn't belong in the scores array.
Change your loop that reads the user input,
so as to not store -1.
Check the input before you store it,
and break out of the loop if it is -1:
while (true) {
double input = read.nextDouble();
if (input == -1) {
break;
}
scores[i++] = input;
}
Btw, what will happen if the user enters 26 values that are not -1?
The program will crash, because scores can only store 25 values.
So you need further some improvements to prevent that from happening.
For example you could use a for loop instead:
for (int i = 0; i < scores.length; i++) {
double input = read.nextDouble();
if (input == -1) {
break;
}
scores[i] = input;
}
I am trying to make a program that takes positive integers from the user and finds the maximum until the user enters a negative number. I have to use a do while loop. It won't accept the variable in the while part of the statement. I don't understand why this is, because I checked and I should have the correct amount of brackets.
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
do {
int currentnumber = 1;
int number = in.nextInt();
if(currentnumber < number) {
currentnumber = number;
}
if(number > currentnumber) {
currentnumber = number;
System.out.println("Max number is: " + currentnumber);
}
} while(number > 0);
Edit: Once I fixed the number issue. The program will print "Enter a number: " but when a number is entered it doesn't do anything
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
int number;
do{
int currentnumber = 1;
number = in.nextInt();
if(currentnumber < number){
currentnumber = number;}
if(number > currentnumber){
currentnumber = number;
System.out.println("Max number is: " + currentnumber);
}
}while(number > 0);
}
}
declare number outside of do block so that while() can access it
No, because in Java, local scopes are defined by {}(block). If you declare number inside the do block, it won't be accessible outside.
Notice that the condition (number > 0) is outside of the do block.
What can you do? You can declare number before the do-while:
int number = ...;
do {
...
} while (number > 0);
To use a variable in the conditional part of a do-while loop, the variable must have scope outside the loop--it must be defined outside the loop.
int number;
do{
int currentnumber = 1;
number = in.nextInt();
if(currentnumber < number) {
currentnumber = number;
} if(number > currentnumber) {
currentnumber = number;
System.out.println("Max number is: " + currentnumber);
}
} while(number > 0);
This is no different from any other loop.
while (number > 0) {
int number;
// do stuff
}
That loop will have obvious problems. But if we rewrite it to:
int number = 1;
while (number > 0) {
// do stuff
}
The problems are gone.
The same logic applies to your do-while loop.
You declared number inside the loop and it therefore only exists within the loop. In order to use it outside of the body of the loop (which includes the loop's conditional statement), it must be declared outside the loop.
One thing I noticed is that you are setting currentnumber in both less than and greater than cases. If you are attempting to determine the max input value then you only need to assign that value if it is greater than the current max value.
One other reason it "doesn't do anything" is likely because the number you have entered is less than the currentnumber. In that case your program doesn't output anything but goes back to accepting input.
Also consider moving the output asking the user for input within the loop. Then each iteration will re-prompt the user for input.
Scanner in = new Scanner(System.in);
int currentMax = 0;
int number = 0;
do {
System.out.println("Enter a number: ");
number = in.nextInt();
if(number > currentMax) {
currentMax = number;
System.out.println("Max number is: " + currentMax);
}
} while(number > 0);
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.
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;