Finding differences of numbers in a for loop - java

I'm a beginner at java and was wondering on how to find the maximum difference between numbers inputted into a for loop. My program takes x amount of odometer readings (Between consecutive trips) from a car, e.g 100km, 150km, 400km, and is supposed to take the maximum distance traveled for all trips, which in this example would be 250km, as well as the minimum which would be 50km and average distance traveled between each odometer reading.
So far i've only managed to find a way to calculate the biggest value and smallest value for each odometer reading, given by the variables maximum and minimum, however have no idea on how to approach or begin to program finding the difference between trips. I tried implementing an array of some sort (not shown in this code) but i keep receiving too many errors. I could really use some advice on how to approach this problem or some insight; it would be greatly appreciated. Thank you for your time.
System.out.print("Input number of trips: ");
carSample.numberOfTrips = input.nextInt();
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
int total = 0;
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i + 1) + ": ");
int odometerReading = input.nextInt();
total += odometerReading;
if (odometerReading > maximum){
maximum = odometerReading;
}
if (odometerReading < minimum){
minimum = odometerReading;
}

int previous = 0;
int minimumTrip = Integer.MAX_VALUE;
int maximumTrip = Integer.MIN_VALUE;
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i + 1) + ": ");
int odometerReading = input.nextInt();
int currentTrip = odometerReading - previous;
if (currentTrip > maximumTrip){
maximumTrip = currentTrip;
}
if (currentTrip < minimumTrip){
minimumTrip = currentTrip;
}
previous = odometerReading;
}
If reading starts not from 0 consider previous = first odometer reading

If you want to calculate the maximum and minimum values of each mileage, the initial values of both are 0, and the maximum and minimum values are updated every time a mileage value is read, and all the mileage values can be obtained by looping .
If you want to calculate the average of all mileage values, then add up all the values divided by the number of values
For example, av = (a + b + c) / 3

Related

Find the biggest difference between indexes

Hey Stackoverflow Community,
I got a little problem where I´m stuck at the moment..
I have to write a code, that have to find the biggest " temperature " difference between given days.
These are my Arrays:
int[] day = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
int[] temperature = {12,14,9,12,15,16,15,15,11,8,13,13,15,12,12,11,7,13,14,11,9,11,10,7,11,6,11,15,10,7};
I need to have an Output like:
The biggest temperature difference was between Day X and Day X with the difference of X Degrees
Can someone give me a hint whats the best way to do it?
Cheers
Hint: A good way to do it in one pass is to keep track of a minimum and maximum, and use those somehow.
More in depth (Don't read if you want to figure it out yourself):
Create a minimum and maximum value to store the index of the min and
max, respectively (can be initialized to 0 and 0)
Loop through each element of the temperatures array
For each element, if it is less than the element at min, change min to the current index
If it is greater than the element at max, change max to the current index
Once you finish, you will have indexes in which the difference is greatest, simply add one to get the day.
Here's some java code:
void greatestDifference(int[] day, int[] temperature) {
int min = 0;
int max = 0;
for(int i = 0; i < temperature.length; i++) {
if (temperature[i] < temperature[min]) {
min = i;
} else if (temperature[i] > temperature[max]) {
max = i;
}
}
int difference = temperature[max] - temperature[min];
System.out.println("The biggest temperature difference was between Day " + (min+1) + " and Day " + (max+1) + ", with the difference of " + difference + " Degrees.");
}
Hope this helped!
Edit: If you plan on having values in day[] that aren't just 1, 2, 3, etc., you can replace the i+1s in the print statement to day[min] and day[max] to get the specific days at which it held those min and max values.
Also, as #SirRaffleBuffle pointed out, the index in the for loop can start at one, since the values at zero would only compare to themselves, but this is not necessary.
Edit 2:
The problem seems to actually have been to find the greatest difference between consecutive days. No worries! Here's some code for that:
import java.lang.Math;
void greatestDifference(int[] day, int[] temperature) {
int max = 0;
for(int i = 0; i < temperature.length-1; i++) {
if (abs(temperature[i] - temperature[i+1]) > abs(temperature[max] - temperature[max+1])) {
max = i;
}
}
int difference = temperature[max+1] - temperature[max];
System.out.println("The biggest temperature difference was between Day " + (max+1) + " and Day " + (max+2) + ", with the difference of " + difference + " Degrees.");
}
This just loops through each value in temperatures and finds the difference between it and the temperature the next day. If the difference is greater than the current max, we update the max. P.S. Math.abs() finds the absolute value.

Minimum Value in an Array java

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

How to find the max value of an unsorted array

I am really new to java and I signed up for an AP class which is being taught very badly, and so I have no idea of how to do this part of the assignment. It prampts you to add code that will do the following
Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., “Salesperson 3 had the highest sale with $4500.” Note that you don’t need another loop for this; you can do it in the same loop where the values are read and the sum is computed.
the code we are given is the following
import java.util.Scanner;
public class Sales {
public static void main(String[] args) {
final int salesPeople = 5;
int[] sales = new int[salesPeople];
int sum;
Scanner scan = new Scanner(System.in);
for (int i=0; i<sales.length; i++) {
System.out.print("Enter sales for salesperson " + i + ":");
sales[i] = scan.nextInt();
}
System.out.println("\nSalesperson Sales");
System.out.println("------------------");
sum = 0;
for (int i=0; i<sales.length; i++) {
System.out.println(" " + " " + sales[i]);
sum += sales[i];
}
System.out.println("\nTotal sales: " + sum);
System.out.println("Average sale " + sum/salesPeople);
}
}
I really do not know what to do and would appreciate a nudge in the right direction as to how to find the max and the id of the person who produced the max.
Please help this is homework!
Because it's your homework, I won't give you the direct answer, but instead give you some hints. If you add two variables, say,
int heighestSale = -1; // assume the sales are not negative or at least one sale is not negative
int heighestPerson = -1;
then you update the two variables based on the current sale value in one of the loops and print out them at the end.
One possible strategy for finding a max value of an unsorted array is to go through the array (using a for loop, perhaps), and keeping track of the maximum value as you go through it.
I don't want to do your homework, but that might look like:
max = Integer.MIN (the smallest possible integer value)
for item in array
if item is greater than max
store item in max
This strategy should find the max value -- hope this helps you! Model the for loops and the print statements like the previous ones you've shown.
The key here is to remember that the sum of all sales and max number of sales can be calculated each time a new salesman's entry is inputted. On the first entry, for example, salesman 0 has N sales -- therefore the sum is N and the max is N. On each consecutive entry, you can update the sum by adding the value to it, and you can update the max if the entry's value is greater than the currently known maximum.

Class ArrayIndexOutOfBoundsException - trying to get rid of it

I am writing a program that will take user input for a random number and number of iterations. I am attempting to do a bubble sort on this (for my class I am required to do it with bubble and selection sorts). My initial code did fine till I worked to add in the portion to do iterations and then the selection sort. Now when I run my code, it will stop and give an error noted in the title of my post. The line it stops at is if randomArray[d]>randomArray[d+1] (the last line in the code below).
From what I have researched in my attempts to resolve this, it says the error is usually thrown when the array has been accessed by illegal index... or the index is negative or greater than the size of the array. I have attempted a few different things to fix this, but at the moment I am at a wall. If anyone can provide some direction, I would greatly appreciate it!
Thanks
Scanner input = new Scanner (System.in);
System.out.println("Enter a number please: ");
int n = input.nextInt();
//Get user input for number if iterations
System.out.println("Enter a number of iterations please: ");
int numIfor = input.nextInt();
//create array of random numbers
int[] randomArray = new int[n];
Random bubbleRandom = new Random();
//fill in the array of random numbers
for(int i=0; i < n; i++) {
randomArray[i] = bubbleRandom.nextInt(100);
}
//Printing the array before the sort
System.out.println("The numbers before the Bubble Sort: ");
for(int i=0; i < n; i++) {
System.out.print(randomArray[i] + " ");
}
System.out.println();
//Printing the array out after the Bubble Sort
int bubble = 0;
int sort = 0;
long startTime = System.currentTimeMillis();
for (int c=0; c < (numIfor - 1); c++)
{
for (int d=0; d < numIfor - c -1; d++)
{
if (randomArray[d]>randomArray[d+1])
{
bubble = randomArray[d];
randomArray[d] = randomArray[d+1];
randomArray[d+1] = bubble;
sort++;
}
}
}
long endTime = System.currentTimeMillis();
long runningTime = endTime-startTime;
System.out.println("The total number of iterations is: " + numIfor);
System.out.println("The total count of numbers sorted is: " + sort);
System.out.println("The total time elapsed was: " + runningTime);
System.out.println("The numbers after the Bubble Sort: ");
for(int i=0; i < n; i++){
System.out.print(randomArray[i] + " ");
}
}
}
What is probably happening is that d+1 is becoming larger than the last position of the array. You can make sure it only goes up to the end of the array by changing the last for loop as such:
The problem here is that you are looping to numIfor, which is a completely independent value from the length of the array (n). This means that if the user enters a numIfor and n, such that numIfor > n, then your code is bound to throw the exception.
The solution to this is using the actual length of the array as the limiter value instead, as such:
for (int c=0; c < randomArray.length-1; c++)
{
for (int d=0; d < randomArray.length-c-1; d++)
{
if (randomArray[d]>randomArray[d+1])
This is assuming that you want d to go through all the values of the array. But the real takeaway here is that you should always try to loop to less than the length of the array (the -1 is there because you are checking for array[d+1]). This works best if you are trying to reach all the values in the array because it guarantees that you don't go out of bounds.

How can I store the biggest value of a set of many values in a variable?

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

Categories

Resources