Finding Max value in for Loop - java

I'm a beginner at java and was just wondering how to find the max and minimum value from integers declared in a for loop (using a scanner to obtain user input) this program creates an object from a class Car and obtains information on the name, registration, colour and number of trips.
The number of trips prompts the for loop to print out odometer readings from 0 (odometer's initial reading) to whatever the variable carSample.numberOfTrips specifies.
I've tried declaring a new variable; int maximum = carSample.odometerReading.MAX_VALUE; (Then printing it)
aswell with minimum, however to no success; I receive the following error:
TestCar.java:25: error: int cannot be dereferenced
int maximum = carSample.odometerReading.MAX_VALUE;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
car carSample = new car(); // Creates object of class Car
carSample.name = input.nextLine();
carSample.registration = input.nextLine();
carSample.colour = input.nextLine();
carSample.numberOfTrips = input.nextInt();
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i) + ": ");
int odometerReading = input.nextInt();
}
Any help or insight into how this can be peformed is really appreciated, thank you for your time!

int maximum = Integer.MIN_VALUE;
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i) + ": ");
int odometerReading = input.nextInt();
if (odometerReading > maximum) {
maximum = odometerReading;
}
}
System.out.println(maximum); // Maximum value

If readings are for example 20 10 22 41 11
Do the first reading. 20
And use that value as your maximum and also minimum. So maximum = 20 and minimum = 20.
Then for the other readings, compare the reading to the current maximum and minimum and update the maximum and minimum accordingly.
E.g: second reading: 10. 10 is less than current maximum of 20, so no change in maximum. 10 is less than current minimum of 20, so update minimum to 10....and repeat for the remainder of the loop.

Related

Why does my Java program not produce a fixed number of random numbers?

I'm very new to Java, most of the time I don't know what I'm doing. I'm trying to make a code where you can choose how many numbers to generate, the maximum and the minimum number of a random number generated.
It keeps on generating the numbers within the max and min range infinitely.
import java.util.Scanner;
import java.util.Random;
public class random_unfinished {
public static void main(String[] args) {
int numofgen, max, min, generated, avg, i;
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("How many numbers would you like to generate?");
numofgen = scan.nextInt();
System.out.println("What is the maximum number?");
max = scan.nextInt() + 1;
System.out.println("What is the minimum number?");
min = scan.nextInt();
for (int value = min; value <= max;) {
value = random.nextInt(max - min) + min;
System.out.println("numbers are " + value);
}
}
}
Okay so the for loop is problematic.
Get used to this:
for (int i = 0; i < n; i++) {
if your for loop doesn't look like that, unless you're quite advanced you're probably doing it wrong.
In your case for instance:
for (int value = min; value <= max;) {
You initialise a variable called value to be the minimum.
Your test to continue is whether value is less than max (which it will be unless min is greater than max)
The thing you do each time after executing the body of the loop is ... nothing.
Hence you loop infinitely.
Compare with the gold standard:
for (int i = 0; i < n; i++) {
It initialises a variable i to 0
Its test whether to continue is if i is less than a certain number n
After each execution of the body of the loop it increments i.
Ergo - unless we do something naughty to i, (or do an early exit with a break or return) we will repeat the body of the loop n times.
Cf:
for (int value = min; value <= max; [_____you forgot this bit____] ) {
The problem is that your for-loop is going from min to max. Also, it is missing an update clause—which means that value never changes. Hence, you’re stuck with an infinite loop.
Instead, you should go from 0 to numofgen and make sure to update your i by 1 each time. This will generate as many numbers as the user desires.
import java.util.Scanner;
import java.util.Random;
public class random_unfinished {
public static void main(String[] args) {
int numofgen, max, min, generated, avg, i;
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("How many numbers would you like to generate?");
numofgen = scan.nextInt();
System.out.println("What is the maximum number?");
max = scan.nextInt() + 1;
System.out.println("What is the minimum number?");
min = scan.nextInt();
for (int i = 0; i < numofgen; i++) {
value = random.nextInt(max - min) + min;
System.out.println("numbers are " + value);
}
}
}

Array keeps counting 0 as a number when I didn'

I'm trying to make a game show program where I enter the number of contestants, how fast they hit the buzzer, the fastest and slowest times for hitting the buzzer, and the number of people that hit the buzzer faster than average.
Everything goes well with my program when I have 5 contestants. But if I enter 4 contestants or anything else less than 5, it messes up some things. When I have 4 contestants, my fastest time is 0, even when I'm not putting in a 0 as a time, and the number of contestants that hit the buzzer faster than average is also messed up, having one extra than it should, because it's putting in a 0.
How do I stop this program from adding in a 0 when I don't have 5 contestants?
import java.util.Scanner;
public class FastestFingers {
public static void main(String[] args) {
//declare varialbes
int contestants;
int [] milisecs = new int [6];
int fastest, slowest, i;
int faster = 0;
double average;
Scanner scanInt = new Scanner (System.in);
//make user enter number of contestants
System.out.println ("Enter # of contestants: ");
contestants = scanInt.nextInt();
//make user enter times
for(i=1;i<=contestants;i++)
{
System.out.println ("Time (ms): ");
milisecs[i] = scanInt.nextInt();
}
//calculate fastest time
fastest = milisecs[1];
for(i=1;i<milisecs.length;i++)
{
if(milisecs[i] < fastest)
{
fastest = milisecs[i];
}
}
System.out.println ("Fastest: " + fastest);
//calculate slowest time
slowest = milisecs[1];
for(i=1;i<milisecs.length;i++)
{
if(milisecs[i] > slowest)
{
slowest = milisecs[i];
}
}
System.out.println ("Slowest: " + slowest);
//tell program how to find average
int total = 0;
for(i=1;i<milisecs.length;i++)
{
total = total + milisecs[i];
}
average = total/contestants;
//find numbers faster than the average
int count = 0;
for(i=1;i<milisecs.length;i++)
{
if(milisecs[i]<average)
{
count++;
}
}
System.out.println ("Faster than average: " + count);
}
}
You create an int[] of fixed size 6. Then you compare the last 5 values to find the lowest. All int values are default 0. If you only set 4 values to anything larger than 0 the fifth value will always be 0 and therefore your lowest value.
You can fix this problem by setting the size of your array to the number of contestants.
Also remember that arrays start counting at 0 not at 1. Your loops should therefore be:
for(i=0;i<milisecs.length;i++), etc.
The problem is that you initialize the array to have six elements.
int [] milisecs = new int [6];
By default all of these values will be zero. Then in your loop you only initialize four of them, meaning that two will still be zero. Change your code to:
System.out.println ("Enter # of contestants: ");
contestants = scanInt.nextInt();
int [] milisecs = new int [contestants];
This will ensure that you will only have as many time slots as you have contestants.
Also array indexes start at zero, so you should change
fastest = milisecs[1];
to
fastest = milisecs[0];
And in your loops, start your variable at 0 instead of 1.
Array Index should start with 0. Please be careful with this. You code reads input and assigns to the milisecs starting from index 1.

print entered integer from input integer to integer

I am trying to obtain two integers as input, and then use these to output another list of integers, using the input as arguments in a loop.
In my code, if I enter low as 1, and high as 10 I expect my output should be the integers 1 through 10. However my code prints the value 1 ten times. I have tried different loops with no luck. Can someone please point out why my output is not as expected?
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the low number: ");
int low = input.nextInt();
System.out.print("Enter the high number: ");
int high = input.nextInt();
//int num1 = low
//int num2 = high
System.out.println("Decimal");
for(int i = low ; low <= high; low++)
System.out.println(i);
}
}
So the issue is that in your for loop you are incrementing the value of low with low++ but you're printing i which you only set to the value of low at the beginning; i doesn't get reset to the value of low on every iteration in your for loop.
So, try changing low++ to i++ and see if that makes a difference ;)
You'll also want to change low <= high to i <= high as we are now incrementing i.

Rolling m die with n sides x times

Okay so I changed my code around and deleted a lot of the unnecessary garbage in it. It works for some numbers but not for others, for example, when I put in 100 rolls/8 sides/3 die it gives me an out of bounds error despite the limits I've set for it. Obviously I've looked over some detail, I'm just not sure what detail it is.
public class Ass11f {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Enter how many times you want to roll the die: ");
int numRolls = console.readInt();
System.out.print("Enter the amount of sides: ");
int numSides = console.readInt();
System.out.print("Enter the amount of die: ");
int numDie = console.readInt();
int[] rollSum = new int[numDie*numSides];
for (int i = 0; i<numRolls; ++i)
{
int rollCounter=0;
for (int l = 0; l<numDie; ++l){
rollCounter += ((int)(Math.random()*numSides)+1);
}
rollSum[rollCounter]++;
}
for (int m = 2;m<=rollSum.length;++m) System.out.println(m+"'s: "+rollSum[m]+" times, "+((((double)rollSum[m])/numRolls)*100)+"%");
}
}
There are two base problems:
When adding roll totals, you're trying to add the maximum roll in an index one past the end of the array. The easy fix is to simply add 1 to the length of your array.
When printing, you cannot access an array using an index equal to the array's length, which is what m<=rollSum.length will eventually do. Replace that with m < rollSum.length so it stops before the final value.
Also, here's some ways to make your array creation a bit clearer:
// The minimum value is always numDie.
// The maximum is always numDie * numSides
// There are maximum - minimum + 1 possible values (ie 6 on a d6)
int maximum = numDie * numSides;
int minimum = numDie;
// Remember, index zero is now the minimum roll.
// The final index is the maximum roll. So the count at an index is really
// the count for any roll with value index + minimum
int[] rollSum = new int[maximum - minimum + 1];
I also recommend splitting up that print statement. It's a bit easier to read and debug. Also, you can start at numDie instead of 2 to account for when you have more or less die than 3:
for (int i = numDie; i < rollSum.length; ++i) {
// Print the first bit, ie "2's: ".
System.out.print(i + "'s: ");
// How many times was that value rolled?
System.out.print(rollSum[i] + " times, ");
// What percentage is that?
double percentage = ((double)rollSum[i]) / numRolls * 100;
System.out.println(percentage + "%");
}

Java While loop skipping lines, doing them every 2 cycles instead

I'm writing a program for homework that is supposed to read in an unspecified number of 0-100 scores (maximum of 100 scores) and stop after -1 or any negative number is entered.
I've put this into a Do While loop that is set to terminate when -1 is pulled in through Scanner. The loop has a counter that keeps track of how many times the loop has been gone through, an adder that adds all the input lines together to later compute an average, and a means to send the input value to an array after it has checked to see if the number is -1.
Instead of doing this, the loop only increments the counter every 2 loops and -1 will only terminate the loop on an even cycle number, other wise it will wait until the next cycle to terminate. This completely baffles me, I have no idea why it's doing this. Could someone point out the error? Thanks in advance! This is all I have so far.
import java.util.Scanner;
public class main {
//Assignment 2, Problem 2
//Reads in an unspecified number of scores, stopping at -1. Calculates the average and
//prints out number of scores below the average.
public static void main(String[] args) {
//Declaration
int Counter = 0; //Counts how many scores are
int Total = 0; //Adds all the input together
int[] Scores = new int[100]; //Scores go here after being checked
int CurrentInput = 0; //Scanner goes here, checked for negative, then added to Scores
Scanner In = new Scanner(System.in);
do {
System.out.println("Please input test scores: ");
System.out.println("Counter = " + Counter);
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
Counter++;
} while ( CurrentInput > 0);
for(int i = 0; i < Counter; i++) {
System.out.println(Scores[i]);
}
System.out.println("Total = " + Total);
In.close();
}
}
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
You are calling twice In.nextInt(), i.e., you are reading two lines in each loop iteration.
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += CurrentInput;
Use this instead.

Categories