Loop validation and output problems - java

So I have everything working except that once I enter the input required I get input like this:
1 5.0
2 6.0
3 7.0
4 8.0
I don't know what I'm doing wrong as it seems its not increasing in the right increments based on the growthRate that I input which was 50. Also can't get the organism number to increase according to the following day. Any suggestions?
//Purpose of program to predict population of organisms
import java.util.Scanner;
public class Population {
public static void main(String[] args) {
double growthRate = -1;
int population = 0;
int days = -1;
double popResult = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("\nEnter the starting number of organisms:");
population = keyboard.nextInt();
while (population < 2) {
System.out.println("\nError!! Please re-enter number of organisms.");
population = keyboard.nextInt();
}
System.out.println("\nEnter rate of growth as percentage:");
growthRate = keyboard.nextInt() / 100;
while (growthRate < 0) {
System.out.println("\nError!! Growth rate must be a positive number. Please re-enter.");
growthRate = keyboard.nextInt();
}
System.out.println("\nEnter number of days organisms will grow:");
days = keyboard.nextInt();
while (days < 0) {
System.out.println("\nError!! Number of days cannot be less than 1. Please re-enter.");
days = keyboard.nextInt();
}
System.out.println("Days" + "\t" + "Organisms");
System.out.println("------------------");
popResult = population;
growthRate = growthRate / 100;
for (int numberOfDays = 1; numberOfDays < days; numberOfDays++) {
System.out.println(numberOfDays + "\t" + popResult);
popResult = (popResult * growthRate) + popResult;
}
}
}

You are taking input for growthRate as Integer format in line
growthRate=keyboard.nextInt()/100;
If it is less than 0 then you take input without dividing by 100 as
growthRate=keyboard.nextInt();
and finally you are again dividing growthRate as
growthRate=growthRate/100;
So you have to take input outside the while loop only as
growthRate=keyboard.nextInt();
Modified code
import java.util.Scanner;
public class Population
{
public static void main(String[] args)
{
double growthRate=-1;
int population=0;
int days=-1;
double popResult=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("\nEnter the starting number of organisms:");
population=keyboard.nextInt();
while(population<2)
{
System.out.println("\nError!! Please re-enter number of organisms.");
population=keyboard.nextInt();
}
System.out.println("\nEnter rate of growth as percentage:");
growthRate=keyboard.nextInt();
while(growthRate<0)
{
System.out.println("\nError!! Growth rate must be a positive number. Please re-enter.");
growthRate=keyboard.nextInt();
}
System.out.println("\nEnter number of days organisms will grow:");
days=keyboard.nextInt();
while(days<0)
{
System.out.println("\nError!! Number of days cannot be less than 1. Please re-enter.");
days=keyboard.nextInt();
}
System.out.println("Days" + "\t" + "Organisms");
System.out.println("------------------");
popResult=population;
growthRate=growthRate/100;
for(int numberOfDays=1; numberOfDays<days; numberOfDays++)
{
System.out.println(numberOfDays + "\t" + popResult);
popResult=(popResult * growthRate) + popResult;
}}}

Related

While loop statement sums all but the first input?

I have a small piece of code that continuously asks the user to input a number until it receives an input that is divisible by 10 (input % 10) and sums all inputs however it does not add the first input
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int input, sum = 0;
System.out.print("Enter a number: ");
input = in.nextInt();
while (input % 10 != 0) {
System.out.print("Enter a number: ");
input = in.nextInt();
sum += input;
if (input % 10 == 0) {
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
}
}
Example run
Enter a number: 15
Enter a number: 27
Enter a number: 45
Enter a number: 50
The total value is: 122
The last input was divisible by 10
The total value is 122 even though it should be 137 because it did not add the first input which is 15
You're tossing the first line away. This seems like a perfect opportunity to use a do-while instead.
Also, you can move the actual printing outside the loop.
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int input;
do {
System.out.print("Enter a number: ");
input = in.nextInt();
sum += input;
} while (input % 10 != 0)
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
Note that this lays on the premise that you still want to add the last value to the sum even if it was divisible by 10.
If that's not what you want, you need to make the addition conditional as well.
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int input;
do {
System.out.print("Enter a number: ");
input = in.nextInt();
if (input % 10 != 0)
sum += input;
} while (input % 10 != 0)
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}

TestScoreStatistics While Loop assistance

We are supposed to create a loop that repeats for the number of times needed by the student. I am completely lost when it comes to setting up a loop that doesn't run on a predetermined count in the code.
We have to create the loop. I dont really even know where to start since there is nothing in the book that I can see that address that style of condition yet.
Any help is appreciated to get me going in the right direction.
import java.util.*;
public class TestScoreStatistics
{
public static void main (String args[])
{
int score;
int total = 0;
int count = 0;
int highest;
int lowest;
final int QUIT = 999;
final int MIN = 0;
final int MAX = 100;
Scanner input = new Scanner(System.in);
System.out.print("How many scores would you like to enter >> ");
enterCount = input.nextInt();
System.out.print("Enter a score >> ");
score = input.nextInt();
//Create a while statement that will loop for the amount entered
while( count != QUIT )
{
}
System.out.print("Enter another score >> ");
score = input.nextInt();
}
System.out.println(count + " scores were entered");
System.out.println("Highest was " + highest);
System.out.println("Lowest was " + lowest);
System.out.println("Average was " + (total * 1.0 / count));
}
}
So. It seems that you want to request entering scores until the user entered as many scores as defined in enterCount:
List<Integer> scores = new ArrayList<Integer>();
while( count < enterCount ) {
System.out.print("Enter another score >> ");
score = input.nextInt();
scores.add(score);
count++;
}
You probably have to define some kind of List where you put the scores in.

Java program will not recognize sentinel value

My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)

Prompt and input numbers and calculate sum, difference, and product

The assignment is to "write a Java program to prompt for and input three numbers. Output the sum of the largest two numbers. Output the difference of the largest and smallest number. Output the product of the smallest two numbers."
I've written the code out but it's not calculating properly. I've included my code below so please feel free to take a look and critique as needed.
import java.util.Scanner;
public class Homework4a {
public static void main (String[] args) {
//Declare Scanner object and three numbers (ints) and ints for smallest and largest numbers
Scanner keyboard;
int firstUsernumber;
int secondUsernumber;
int thirdUsernumber;
int largestnumber;
int smallestnumber;
int largestnumber2;
int smallestnumber2;
int largestnumber3;
int smallestnumber3;
//Instantiate keyboard
keyboard = new Scanner(System.in);
//Prompt the user for input
System.out.print("Enter your first number here: ");
//Obtain and store first number
firstUsernumber = keyboard.nextInt();
//Prompt the user for second input
System.out.print("Enter your second number here: ");
//Obtain and store the second input
secondUsernumber = keyboard.nextInt();
//Prompt the user for third input
System.out.print("Enter your third number here: ");
//Obtain and store the second input
thirdUsernumber = keyboard.nextInt();
//Determine largest number
if (firstUsernumber > secondUsernumber) {
largestnumber = firstUsernumber;
smallestnumber = secondUsernumber;
} else {
largestnumber = secondUsernumber;
smallestnumber = firstUsernumber;}
if (secondUsernumber > thirdUsernumber) {
largestnumber2 = secondUsernumber;
smallestnumber2 = thirdUsernumber;
} else {
largestnumber2 = thirdUsernumber;
smallestnumber2 = secondUsernumber;}
if (firstUsernumber > thirdUsernumber) {
largestnumber3 = firstUsernumber;
smallestnumber3 = thirdUsernumber;
} else {
largestnumber3 = thirdUsernumber;
smallestnumber3 = firstUsernumber;
}//Ending bracket of if statement
//Calculate sum of largest numbers
System.out.println("The sum of the largest numbers is: " + (largestnumber + largestnumber2));
//Calculate the difference of the largest and smallest number
System.out.println("The difference of the largest number and smallest number is: " + (largestnumber - smallestnumber));
//Calculate the product of the smallest numbers
System.out.println("The product of the smallest numbers is: " + (smallestnumber*smallestnumber3));
}//Ending bracket method main
}//Ending bracket class Homework4a
import java.util.Scanner;
//this program takes three integers from the user and outputs the sum of the largest two numbers, the difference of the largest and smallest number, and the product of the smallest two numbers.
// done by Nadim Baraky
public class OperationsOnNumbers {
public static void main(String[] args) {
//declare three integer variables
int firstMax, secondMax, min;
//firstMax: largest number; secondMax: the number in between; min: the smallest number.
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
int firstNumber = input.nextInt();
System.out.print("Enter your second number: ");
int secondNumber = input.nextInt();
System.out.print("Enter your third number: ");
int thirdNumber = input.nextInt();
input.close();
firstMax = Math.max(Math.max(firstNumber, secondNumber),thirdNumber);
if(firstMax == firstNumber) {
secondMax = Math.max(secondNumber, thirdNumber);
}
else if(firstMax == secondNumber) {
secondMax = Math.max(firstNumber, thirdNumber);
}
else {
secondMax = Math.max(firstNumber, secondNumber);
}
min = Math.min(Math.min(firstNumber, secondNumber), thirdNumber);
System.out.println("The sum of the largest two numbers is: " + (firstMax + secondMax));
System.out.println("The difference of the largest and smallest numbers is: " + (firstMax - min));
System.out.println("The product of the smallest two numbers: " + secondMax * min);
}
}

Using the while loop to ask user their input in JAVA

I have like 3 hours trying to solve this simple problem. Here is what I am trying to accomplished: Ask the user to enter a number, and then add those numbers. If the users enters five numbers, then I should add five numbers.
Any help will be appreciated.
import java.util.Scanner;
public class loopingnumbersusingwhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input;
System.out.println("How Many Numbers You Want To Enter");
total = kb.nextInt();
while(input <= kb.nextInt())
{
input++;
System.out.println("How Many Numbers You Want To Enter" + input);
int input = kb.nextInt();
}
}
}
Your current code is trying to use input for too many purposes: The current number entered, the amount of numbers of entered, and is also trying to use total as both the sum of all numbers entered and the amount of numbers to be entered.
You'll want 4 separate variables to track these 4 separate values: how many numbers the user will entered, how many they entered so far, the current number they entered, and the total.
int total = 0; // The sum of all the numbers
System.out.println("How Many Numbers You Want To Enter");
int count = kb.nextInt(); // The amount of numbers that will be entered
for(int entered = 0; entered < count; total++)
{
int input = kb.nextInt(); // the current number inputted
total += input; // add that number to the sum
}
System.out.println("Total: " + total); // print out the sum
Add this code after you take how many numbers the user wants to add:
int total;
for(int i = 0; i < input; i--)
{
System.out.println("Type number: " + i);
int input = kb.nextInt();
total += input;
}
To print this just say:
System.out.println(total);
import java.util.Scanner;
public class LoopingNumbersUsingWhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input=0;
int total = 0;
System.out.println("How Many Numbers You Want To Enter");
int totalNumberOfInputs = kb.nextInt();
while(input < totalNumberOfInputs)
{
input++;
total += kb.nextInt();
}
System.out.println("Total: " +total);
}
}
You seem to be asking how many numbers twice.
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter");
int howMany = kb.nextInt();
int total = 0;
for (int i=1; i<=howMany; i++) {
System.out.println("Enter a number:");
total += kb.nextInt();
}
System.out.println("And the grand total is "+total);
}
What you should pay attention to:
name classes in CamelCase starting with a big letter
initialize total
don't initialize input twice
show an appropriate operand input request to your user
take care of your loop condition
don't use one variable for different purposes
which variable should hold your result?
how to do the actual calculation
Possible solution:
import java.util.Scanner;
public class LoopingNumbersUsingWhile {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter: ");
int total = kb.nextInt();
int input = 0;
int sum = 0;
while (input < total) {
input++;
System.out.println("Enter " + input + ". Operand: ");
sum += kb.nextInt();
}
System.out.println("The sum is " + sum + ".");
}
}

Categories