Why wont Min and Max num update - java

Very new to Java (please don't laugh)and trying to do a project that asks user for a number and will keep track of the highest and lowest number when the user enter a sentinel value. My error is the I cannot get max and min values to update when going through the while loop.
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double number, or 'q' to quit");
double currentNum = 0.0;
double maxNum=0.0;
double minNum=0.0;
int count = 0;
while(sc.hasNextDouble())
{
currentNum = sc.nextDouble();
count++;
System.out.println(count);
if(count ==1)
{
minNum = currentNum;
maxNum = currentNum;
System.out.println("Please enter a double number, or 'q' to quit");
}
else if(count!=1){
if (currentNum > maxNum)
{
currentNum = maxNum;
System.out.println("You are in currentNum > maxNum");
System.out.println(maxNum);
System.out.println("Please enter a double number, or 'q' to quit");
System.out.println(maxNum);
}
else if (currentNum < minNum)
{
currentNum = minNum;
System.out.println("You are in currentNum < minum");
System.out.println("Please enter a double number, or 'q' to quit");
}
}
}
System.out.println("Min num " + minNum);
System.out.println("Max num " + maxNum);
}
}

I think you got your logic mixed up.
When you get a number larger or smaller than maxNum you want to update maxNum to currentNum not the other way around.
Also the count == 1 if condition is redundant.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double number, or 'q' to quit");
double currentNum = 0.0;
double maxNum=(double)Integer.MIN_VALUE;
double minNum=(double)Integer.MAX_VALUE;
int count = 0;
while(sc.hasNextDouble()) {
currentNum = sc.nextDouble();
count++;
System.out.println(count);
if (currentNum > maxNum){
maxNum = currentNum;
System.out.println("You are in currentNum > maxNum");
System.out.println("Maximum : "+maxNum);
}
else if (currentNum < minNum){
minNum = currentNum;
System.out.println("You are in currentNum < minum");
System.out.println("Minimum : "+minNum);
}
System.out.println("Please enter a double number, or 'q' to quit");
}
System.out.println("Min num " + minNum);
System.out.println("Max num " + maxNum);
}
}

One thing that I noticed is that you're comparing double variables. Generally it's not a good idea comparing floating point values because they have precision problems. You should use long or int instead. If you really don't have any other choice and have to use double, you should checkout this question: How to compare two double values in Java?
As pointed out in comment, you're updating currentNum instead of maxNum/minNum. So your else-if block for updating min-max value should look like this:
if (currentNum > maxNum) {
System.out.printf("You are in currentNum(%d) > maxNum(%d)", currentNum, maxNum);
//currentNum = maxNum; // <- Wrong, doesn't update maxNum; currentNum would be updated in next loop iteration anyway
maxNum = currentNum; // <- What you should be doing
}
else if (currentNum < minNum) {
System.out.printf("You are in currentNum(%d) < minNum(%d)", currentNum, minNum);
//currentNum = minNum; // <- Wrong, doesn't update minNum
minNum = currentNum; // <- What you should be doing
}

Related

Java Scanner input validation causing loop to end early

I am filling a Double Array with a for-loop, the loop runs for how many laps the user enters on line 4. However, as I demonstrate in my picture included:
I enter 3 laps and the question prompts 3 times however my data validation eats one of the inputs I am looking for.
How do I fix this? I feel like its something very simple.
import java.util.Scanner;
public class JK_FINALPRAC1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Time-Trial Statistics Program\n");
System.out.println("This program will ask you to input split-times for each lap or length of a race. The ");
System.out.println("program will then calculate some basic statistics from the split-times.\n");
System.out.print("Enter the number of laps or lengths in the race: ");
int arraySize = sc.nextInt();
Double[] lapArray = new Double[arraySize];
System.out.println("Now input the elapsed time (split time) in seconds for each lap/length of the race.");
int index = 1;
double currentNum = 0.0;
for(int i=0;i<arraySize;i++){
System.out.print("Time for lap or length #" + index + ": ");
currentNum = sc.nextDouble();
if(currentNum > 0 && currentNum < 61){
lapArray[i] = currentNum;
index++;
}else if(currentNum<0 || currentNum >60){
System.out.println("Invalid input! Time must be between 0 and 60.");
}
}
}
double currentNum = 0.0;
while (index < arraySize) {
System.out.print("Time for lap or length #" + (index + 1) + ": ");
currentNum = sc.nextDouble();
if (currentNum > 0 && currentNum < 61) {
lapArray[index] = currentNum;
index++;
} else if (currentNum < 0 || currentNum > 60) {
System.out.println("Invalid input! Time must be between 0 and 60.");
}
}
Since you're running for-loop, i is getting incremented every time (even if your validation fails).
It's very simple: in order to be sure you have inserted a double without eat a lap, put your scanner input line inside a while-loop
do{
double x = scanner.nextDouble();
}while(x < 0 || x > 60);
This will not afford for-loop increasing counter, unless the condition of do-while is false.
In order to print validation, too:
double x = scanner.nextLine();
while( x < 0 || x > 60){
//print message
//scanner again
}

Java loop until user enters a value of 0. The values must be between 1-4 and if over 4, ask user to try inputting again

I need to create a loop where the user can input any amount of numbers between 1-4 and then I calculate the average. Typing 0 will end the program and calculate the average. Any value greater than 4 or less than 0 should not count and ask the user to input the value again. I'm stuck on the last part. I'm not sure if the while loop is the correct loop to use either. Thanks for any help
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0)
break;
if (num > 4)
System.out.println("Invalid number");
sum += num;
count += 1;
}
System.out.println("Average: " + sum/count);
}
You will always hit the lines:
sum += num;
count += 1;
Because the code just drops through from the second if statement.
The following would work - note the else if and else blocks will only be executed when the first if drops through:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0) {
break;
}
else if (num > 4) {
System.out.println("Invalid number");
}
else {
sum += num;
count += 1;
}
}
System.out.println("Average: " + sum/count);
}

Print out Average in for loop

This is my question
get to input a positive integer representing a number of weeks, loop
continuously until the value entered is positive. For each week, enter
a value for liters and a value for kilometers. For each value, should
loop until the value entered is positive. both values is a real
number. Then output the fuel economy for that week (liters divided by
kilometers). Finally, output the average fuel economy. You must make
good use of submodules in your answer.
This is my work
import java.util.*;
public class Exam8 {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (true) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum = result + (double)count;
System.out.println(result);
}
//average = getAverg(sum,count);
System.out.print("Average of fuel economy is: " + average);
}
public static double getAverg(double sum, int count) {
double average;
average = sum/count;
return average;
}
}
I get a problem when input value of lit and km, for example, I like to stop when to put either of a value of lit or km. Then I have another problem with outputting an average of the result (lit/km).
This code should work:
import java.util.*;
public class App {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (count < numweek) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum += result;
System.out.println(result);
}
System.out.print("Average of fuel economy is: " + getAverg(sum, numweek));
}
public static double getAverg(double sum, double numOfWeeks) {
double average;
average = sum/numOfWeeks;
return average;
}
}
Your first error was that the condition in the while loop wasn't correct. In order for the loop to stop you need to specify proper conditions. If condition is true it will loop indefinetely or until you set break.
Your second error was that you didn't calculate the average correctly. You should have just taken the sum for every week and added it to the current sum(which is zero at the beggining), and then just divide that sum by number of weeks to get the average.
You also didn't use your getAverg function anywhere.

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

while loop - sum of even numbers and its average

http://pastebin.com/w8KntkE6#
package javaapplication9;
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication9 {
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
while (num >= 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0) {
count++;
sum += num;
System.out.println("The sum so far is " + sum);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
} else if (num % 2 != 0) {
continue;
}
System.out.println();
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
}
}
}
The code executes and it sums even numbers. However, when a odd number enters it returns an error or it breaks. I want it ignore any odd number. What is wrong with my code?
You continue the loop on odd numbers without modifying num - looks like it should infinite loop to me.
Am I missing something, or are you missing a nextInt() when you have an odd number? Since in the if even you have num = scan.nextInt();. You don't when num is odd.
Change
else if (num % 2 != 0){
continue;
}
to
else if (num % 2 !=0){
num = scan.nextInt();
continue;
}
just before continue statement add following code. I hope it will work correctly.
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
Change to:
package javaapplication9;
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication9 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
while (num >= 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0)
{
count++;
sum += num;
System.out.println("The sum so far is " + sum);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
num = scan.nextInt();
}
}
Try this. I'm not quite sure when do you want to print the average, you could move it out of the while loop if you want to print it at the end.
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
while ((num = scan.nextInt())> 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0){
count++;
sum += num;
System.out.println("The sum so far is " + sum);
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
System.out.print("Enter an integer (0 to quit): ");
}
System.out.println("end");
}
}

Categories