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");
}
}
Related
I'm writing a java program to take a bunch of doubles the user inputs into the command line, add them together, and average them. The user can enter any amount of numbers. When they enter a negative number, the program does the adding/averaging. When i enter a number into cmd line it only lets me enter one. Can anyone help me improve this?
import java.util.Scanner;
public class Average
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Statistics Program, assignment one, program
Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop,
enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
int amount = 0;
double totaladded = 0;
double userinput = 0;
userinput = keyboard.nextDouble();
while (userinput >= 0);
{
if(userinput > 0 )
{
totaladded = totaladded+userinput;
amount++;
}
}
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
}
use a do while loop instead,
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int amount = 0;
double totaladded = 0;
double userinput = 0;
do {
System.out.println("Statistics Program, assignment one, program Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop, enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
userinput = keyboard.nextDouble();
if(userinput > 0 ) {
totaladded += userinput;
amount++;
}
} while (userinput >= 0);
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
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);
}
}
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;
}}}
So I am taking Java as part of math degree requirements and have stumbled on a problem with this code. Essentially the code is supposed to take in numbers from the user until they type a zero. It works fine as long as only numbers are entered. However if the user enters a letter or symbol the program gets an exception. Is there a simple way I can validate user input as a number without getting an exception?
import java.util.Scanner;
public class SamsAdder
{
public static void main(String[] args)
{
double userInput = 1;
double sum = 0;
Scanner in = new Scanner (System.in);
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
}
System.out.println("The sum of the numbers is " + sum + ".");
}
}
So I've tried the try/catch as you showed it. I'm still getting an exception with non numbers though. Entered the code as follows:
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
try{
userInput = in.nextDouble();
}
catch(NumberFormatException nfe){
System.out.println("Invalid Number");
}
sum = sum + userInput;
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class SamsAdder {
public static void main(String[] args) {
double userInput = 1;
double sum = 0;
Scanner in = new Scanner(System.in);
while (userInput != 0) {
try {
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
} catch (InputMismatchException nfe) {
System.out.println("Invalid Number");
in.next();
}
}
in.close();
System.out.println("The sum of the numbers is " + sum + ".");
}
}
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 + ".");
}
}