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];
}
}
}
Related
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);
}
The purpose of this method is to iterate through a 2D array of integers called grid[][], and translate the integers based on the maximum and minimum values into a smaller range between 100 and 250 (the original minimum value becomes 100, the original maximum value becomes 250, and everything in between is calculated respectively). When this method is called, division by zero ArithmeticException occurs.
Clearly I'm making some logic mistakes here... I just don't see the fix. Can anyone help?
public int greenValues(int arrayVal) {
int max = 0;
int min = 0;
int colorValue = 0;
int temp;
for (int i = 0; i < grid.length; i++) { // finds maximum and minimum numbers in file
for (int j = 0; j < grid.length; j++) {
if (max < grid[i][j]) {
max = grid[i][j];
}
if (min > grid[i][j]) {
min = grid[i][j];
}
}
}
int arrayRange = (max-min); // arrayVal, arrayRange, and max and min are 0
temp = (((arrayVal-min) * COLOR_RANGE) / arrayRange) + 100; // map values to range of 100 - 250
colorValue = temp;
return colorValue;
}
This line is culprint for producing ArithmaticExcpetion.
temp = (((arrayVal-min) * COLOR_RANGE) / arrayRange) + 100;
your calculating arrayRange dynamically as you don't know when that value will be 0. so you can wrap this line with try catch block to do some exception handling.
Solution by Dilip is perfect. Or you can also add a conditional statement which lets it pass only when arrayRange is not 0 & execute something else if it is 0. But it'll increase overhead by executing the conditional statement every time arrayRange is calculated.
When I try to run this program in java it will not work even though there are no errors in eclipse.
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter how many numbers: ");
int x = input.nextInt();
double[] numbers = new double[x];
double[] orderednumbers = new double[x];
double total = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print("Please enter number " + (i + 1) + ": ");
numbers[i] = input.nextDouble();
total += numbers[i];
}
double mean = (total / x);
System.out.println("Mean: " + mean);
orderednumbers[x] = 0;
for (int counter = 0; counter < numbers.length; counter++) {
if (numbers[counter] > orderednumbers[x]) {
orderednumbers[x] = numbers[counter];
orderednumbers[x] = orderednumbers[x];
}
}
System.out.println("Maximum: " + orderednumbers[x]);
}
}
This is what's called a runtime error. Sure, it compiles... but for this code you need to be careful with how you handle the array. Your code gave me an ArrayOutOfBoundsException.
Note that you set x early in the code to the length of the array, then go and set orderednumbers[x] to 0. This will give you an ArrayIndexOutOfBoundsException, as since Java array indices are zero-based (i.e. element #1 has index 0, and can be accessed with orderednumbers[0]), the length of an array isn't a valid index.
Also, your code for swapping the two numbers in the sort is incorrect; you'll need a temporary variable to store the result. Otherwise, you'll end up making the two places in the array hold the same value.
Try making it this:
int temp = orderednumbers[x];
orderednumbers[x] = numbers[counter];
orderednumbers[x] = temp;
Note that your statement at the end of the if block:
orderednumbers[x] = orderednumbers[x];
won't accomplish anything.
Im using an array that lets the user choose a certain amount of of variables, and each one of these variables will become a random number. However, how can I take the biggest of those random numbers and store it in a variable? Im fairly new at Java, so a simple, understandable way to do this would be perfect. Thanks in advance!
int [] arr;
Scanner reader= new Scanner(System.in);
n = reader.nextInt();
array = new int [n];
for (n = 0; n < array.length; n++ )
{
x = (int)(Math.random() * 10) + 1;
System.out.println(x);
System.out.println("Biggest Value is: " + );
}
You may use an integer variable to keep track of the highest number. While iterating if you come across a number greater than highest variable, make that number as highest and continue iterating till the end of the loop.
int highest = Integer.MIN_VALUE;
for (n = 0; n < array.length; n++ ){
x = (int)(Math.random() * 10) + 1;
if(x > highest){
highest = x;
}
}
System.out.println("Highest number is " + highest);
I"m trying to make a program that retrieves an endless amount of numbers that user inputs, and then it tells you how many numbers that you inputted, the sum of all the numbers, and then the average of the numbers. Here is the code I have so far. I don't know why it does not work. I get no errors, but it just does not get a valid sum or average.
import javax.swing.*;
public class SumAverage {
public static float sum;
public static float averageCalculator;
public static float average;
public static void main(String[]args) {
float numbers[] = null;
String userInput = JOptionPane.showInputDialog(null, "Ready to begin?");
if(userInput.equalsIgnoreCase("no"))
{
System.exit(0);
}
for(int i = 0; i != -2; i++)
{
numbers = new float[i + 1];
userInput = JOptionPane.showInputDialog(null, "Input any number. Input * to exit");
if(userInput.length() == 0 || userInput.equals("*") || userInput.equals(null))
{
break;
}
else
{
numbers[i] = Float.parseFloat(userInput);
}
}
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
average = sum / numbers.length;
JOptionPane.showMessageDialog(null, "The sum of all your numbers is " + sum + ". The average is " + average + ". You entered a total of " + numbers.length + " numbers.");
}
}
The problem is in this line:
numbers = new float[i + 1];
You are creating a new array, but you aren't copying the values from the previous array assigned to numbers into it.
You can fix this in two ways:
copy the values using System.arraycopy() (you'll need to use a new variable to make the call then assign it to numbers)
Don't use arrays! Use a List<Float> instead, which automatically grows in size
In general, arrays are to be avoided, especially for "application logic". Try to always use collections - they have many powerful and convenient methods.
If you wanted to store the numbers for later use, try making your code look like this:
List<Float> numbers = new ArrayList<Float>();
...
numbers.add(Float.parseFloat(userInput));
...
for (float n : numbers) {
sum += n;
}
average = sum / numbers.size(); // Note: Don't even need a count variable
And finally, if you don't need to store the numbers, just keep a running sum and count and avoid any kind of number storage.
Unrelated to the Q, but note also you can compute a running count/average without storing all the input data - or assuming you want to keep the input - without traversing over it each iteration. Pseudocode:
count = 0
sum = 0
while value = getUserInput():
count++
sum += value
print "average:" + (sum / count)
with
numbers = new float[i + 1];
you are creating a whole new array on every iteration. That means you are always creating a new array that will increase its size by 1 on each iteration but only having one field filled with the current user input and having all the other fields been empty.
Delete this line and initialize the array before.
If the size of the array should grow dynamically within the loop
do not use an array at all and use a dynamic data structure like a List or an ArrayList instead.
Further i would suggest to use
while (true) {
//...
}
to realize an infinite loop.