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

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

Related

Storing multiple values inside a while loop - Java

I'm trying to store the sum of 2 numbers inside a while loop so that once the loop ends multiple sums can be added up and given as a total sum, however I am rather new to Java and am not sure how to go about doing this.
I'm trying to use an array but I'm not sure if it is the correct thing to use. Any help would be greatly appreciated.
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
Int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[0]=AddedNum;
TotalNum[1]=;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
System.out.println("The total sum of all the numbers you entered is " + TotalNum);
}
}
There is a data container called ArrayList<>. It is dynamic and you can add as many sums as you need.
Your example could be implemented like this:
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> listOfSums = new ArrayList<>();
int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
listOfSums.add(AddedNum);
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
// Then you have to calculate the total sum at the end
int totalSum = 0;
for (int i = 0; i < listOfSums.size(); i++)
{
totalSum = totalSum + listOfSums.get(0);
}
System.out.println("The total sum of all the numbers you entered is " + totalSum);
}
}
From what I see, you come from a background of C# (Since I see capital letter naming on all variables). Try to follow the java standards with naming and all, it will help you integrate into the community and make your code more comprehensible for Java devs.
There are several ways to implement what you want, I tried to explain the easiest.
To learn more about ArrayList check this small tutorial.
Good luck!
Solution with array:
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
int Num1, Num2, AddedNum;
String answer;
int count = 0;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[count]=AddedNum;
count++;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
int TotalSum = 0;
for(int i = 0; i <count; i++ ) {
TotalSum += TotalNum[i];
}
System.out.println("The total sum of all the numbers you entered is " + TotalSum);
}
}
This solution is not dynamic. There is risk that length of array defined on beginning will not be enough large.

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

populating the array with the user input

i apologize i know this looks simple but i'm kinda new to coding. the goal of the program is to take inputs from the user starting at index 0 and then save the inputs into the array. i'm probably close to solving this but i need some help.
here is the code:
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[numberOfGrades] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
Your logic is a bit off. numberOfGrades is the.. well.. number of grades. And when you do this: grades[numberOfGrades] = input.nextInt(); then you put the user's input in the grades array in location numberOfGrades, which you don't want.
What you do want is:
do {
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
This way, the array in location counter is accessed, and the user's input is placed inside it in the correct location.
Also, to calculate the average of the grades, like you are trying to do in the end of your program, you should do:
double sum = 0;
for (int grade : grades)
sum += grade;
And then your average will be:
average = 1.0d * sum / grades.length;
You can just as well put this summing logic inside your do-while loop and avoid the extra loop I introduced.
this instruction
grades[numberOfGrades] = input.nextInt();
must be replaced by
grades[counter] = input.nextInt();
try this ...
The thing that you were doing wrong is in the do while loop you were inserting value in the same array index grades[numberOfGrades] = input.nextInt(); should be replaced by grades[counter] = input.nextInt();
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
You can try like this
public class ArrayTest {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("enter number of elements");
int n=input.nextInt();
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++){//for reading array
arr[i]=input.nextInt();
}
for(int i: arr){ //for printing array
System.out.println(i);
}
}

Min and Max Values [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have to make code to find the max, min, and average of grades. This is what I have so far:
public class test
{
public static void main (String[] args)
{
double average, count = 0, sum = 0, grades, max=0, min=0;
final int = MAX_GRA = 0
final int = MIN_GRA = 0
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the grades (999 to quit): "); //Taking input from the user
grades = scan.nextInt();
while (grades != 999) //A while loop that doubles count and adds the sum to grades
{
count++;
sum += grades;
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter the grades (999 to quit): ");
grades = scan.nextInt();
}
System.out.println ();
if (count == 0) //An if statement that identifies if no numbers were entered
System.out.println ("No grades were entered.");
else //An else statement that computes that computes the average
{
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println ("The average grade is " + fmt.format(average));
}
}
}
Any ideas? I'm new to java and coding in general. Thank you for your time!
You could try something like this:
int maxGrade = 0;
int minGrade = 10; // Set the highest possible grade.
while (grades != 999)
{
// If the current grade is greater that the maxGrade,
// set this value the maxGrade.
if(grades > maxGrade)
maxGrade = grades;
// If the current grade is less than the minGrade,
// set this value to the minGrade.
if(grades < minGrade)
minGrade = grades;
// Here you will place the rest of your code.
}
Note: Try to use more meaningful names for your variables. This will make your code more readable and it convey far easier your intentions and thoughts to the reader of your code. For instance, since grades would keep the value of the current grade, it would be more reasonable to name it as grade.
Update
As correctly laune mentioned below you could make use of two methods of Math class, in order to avoid the if statements.
while (grades != 999)
{
maxGrade = Math.max(maxGrade, grades);
minGrade = Math.min(minGrade, grades);
}
I would change somethings in the original code, and put like this.
public class Grades {
// MODIFIERS (final, private, protected, static, etc.) type (int, double,
// float, Object, etc.) name [= initialValue];
private final static double END_GRADES = 999;
public static void main(String[] args) {
double count, sum, grades, max, min;
Scanner scan = new Scanner(System.in);
// Initialized data.
count = 0;
sum = 0;
max = 0;
min = 0;
do {
System.out.println("Enter next grade ("+(int)END_GRADES+" to quit):");
grades = scan.nextDouble();
if (grades != END_GRADES) {
if (count == 0) { // First grade is always min.
min = grades;
}
sum = sum + grades;
count++;
System.out.println("The sum so far is: " + sum);
if (max < grades) { // New max??
max = grades;
}
if (min > grades) { // New min??
min = grades;
}
}
} while (grades != END_GRADES);
if (count != 0) {
System.out.println("The average grade is: " + (sum / count));
System.out.println("The max grade is: " + max);
System.out.println("The min grade is: " + min);
} else {
System.out.println("No grades were entered.");
}
}
}
Look like you took half the way to the answer, but I assume you are missing the min,max values as you average and sum are already computed.
First you need to add two instruction to update your maximum and minimum variables grade holders and the short way to do is to use:
Math#max shorthand comparison returning the max of arguments.
Math#min shorthand comparison returning the min of arguments.
But you have to remove the final modifier in front of the MAX_GRA and MIN_GRA because those instance variables need to be update at each iteration in your while loop so that they get either the user entered grade or keep their own value.
You should then take care of variables declaration, so that comparisons will take place and to do so, you can set the min value to the maximum possible one in the integer range and vice vers ça.
Last you need to add print statement simply to show you max / min value along with your average of grades:
public class MinMaxAndAverageCalculator
{
public static void main (String[] args)
{
double average, count = 0, sum = 0, max=0, min=0;
int MAX_GRA = Integer.MIN_VALUE;
int MIN_GRA = Integer.MAX_VALUE;
int grade;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the grades (999 to quit): "); //Taking input from the user
grade = scan.nextInt();
while (grade != 999) //A while loop that doubles count and adds the sum to grades
{
count++;
sum += grade;
MAX_GRA = Math.max(grade, MAX_GRA);
MIN_GRA = Math.min(grade, MIN_GRA);
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter the grades (999 to quit): ");
grade = scan.nextInt();
}
if (count == 0) //An if statement that identifies if no numbers were entered
{
System.out.println("No grades were entered.");
}
else //An else statement that computes that computes the average
{
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println ("The average grade is " + fmt.format(average));
System.out.println ("The maximum grade is " + MAX_GRA);
System.out.println ("The minimum grade is " + MIN_GRA);
}
}
}

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