This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 3 years ago.
I created a Java program that accepts three integers and would print the sum, product, the smallest and largest, and the average of these three integers.
import java.util.Scanner;
public class ThreeNums
{
public static void main (String[] args)
{
new ThreeNums();
}
public ThreeNums ()
{
int num1, num2, num3, sum, smallest, largest, exitPrompt = 0;
float average;
Scanner scan = new Scanner (System.in);
while (exitPrompt == 0)
{
System.out.printf ("\n\nPlease enter three integers.\n");
System.out.printf ("\t1st integer: ");
num1 = scan.nextInt();
System.out.printf ("\t2nd integer: ");
num2 = scan.nextInt();
System.out.printf ("\t3rd integer: ");
num3 = scan.nextInt();
System.out.printf ("\n");
sum = num1+num2+num3;
System.out.println ("Sum: " + sum);
System.out.printf ("Product: %d\n", num1*num2*num3);
if (num1<num2)
smallest = num1;
else
smallest = num2;
if (smallest<num3)
smallest = smallest;
else
smallest = num3;
if (num1>num2)
largest = num1;
else
largest = num2;
if (largest>num3)
largest = largest;
else
largest = num3;
System.out.printf ("Smallest integer: %d\n", smallest);
System.out.printf ("Largest integer: %d\n", largest);
average = sum/3;
System.out.printf ("Average: %.3f\n", average);
System.out.printf ("\nExit? 0 if NO, any other digit if YES\n");
exitPrompt = scan.nextInt();
}
System.out.printf ("\n\n");
}
}
Everything is okay except (I think) at lines 56-57:
average = sum/3;
System.out.printf ("Average: %.3f\n", average);
It is supposed to print the average of the three integers the user will input. For example, if the user inputs 5, 7, and 7, it is supposed to show that the average is 6.333:
Please enter three integers.
1st integer: 5
2nd integer: 7
3rd integer: 7
Sum: 19
Product: 245
Smallest integer: 5
Largest integer: 7
Average: 6.333
Exit? 0 if NO, any other digit if YES
But instead, for the average, it shows only 6.000.
.
.
.
Average: 6.000
.
.
If I input 78, 45, and 23, it only shows 48.000 instead of 48.667, and so on. What could be the problem with my code? Please help... Thanks!
Here: average = sum/3; both sum and 3 are ints, so the result is an int and then it's conferted into float. You can overcome this with this:
average = sum / 3.0;
Related
I've got an assignment that requires me to use a loop in a program that asks the user to enter a series of integers, then displays the smallest and largest numbers AND gives an average. I'm able to write the code that allows the user to enter however many integers they like, then displays the smallest and largest number entered. What stumps me is calculating the average based on their input. Can anyone help? I'm sorry if my code is a little janky. This is my first CS course and I'm by no means an expert.
import javax.swing.JOptionPane;
import java.io.*;
public class LargestSmallest
{
public static void main(String[] args)
{
int number, largestNumber, smallestNumber, amountOfNumbers;
double sum, average;
String inputString;
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
largestNumber = number;
smallestNumber = number;
sum = 0;
for (amountOfNumbers = 1; number != -99; amountOfNumbers++)
{
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
if (number == -99)
break;
if (number > largestNumber)
largestNumber = number;
if (number < smallestNumber)
smallestNumber = number;
sum += number;
}
average = sum / amountOfNumbers;
JOptionPane.showMessageDialog(null, "The smallest number is: " + smallestNumber + ".");
JOptionPane.showMessageDialog(null, "The largest number is: " + largestNumber + ".");
JOptionPane.showMessageDialog(null, "The average off all numbers is: " + average + ".");
}
}
The problem is that you do an extra
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
at the beginning. You don't count that in a sum. That's why you get unexpected results.
The fix would be:
replace the declarations line with:
int number = 0, largestNumber, smallestNumber, amountOfNumbers;
Remove
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
That go before the loop
Replace for (amountOfNumbers = 0 with for (amountOfNumbers = 1
This is my first CS course
Then allow me to show you a different way to do your assignment.
Don't use JOptionPane to get input from the user. Use a Scanner instead.
Rather than use a for loop, use a do-while loop.
Usually you declare variables when you need to use them so no need to declare all the variables at the start of the method. However, be aware of variable scope.
(Notes after the code.)
import java.util.Scanner;
public class LargestSmallest {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int largestNumber = Integer.MIN_VALUE;
int smallestNumber = Integer.MAX_VALUE;
int number;
double sum = 0;
int amountOfNumbers = 0;
do {
System.out.print("Enter an integer, or enter -99 to stop: ");
number = stdin.nextInt();
if (number == -99) {
break;
}
if (number > largestNumber) {
largestNumber = number;
}
if (number < smallestNumber) {
smallestNumber = number;
}
sum += number;
amountOfNumbers++;
} while (number != -99);
if (amountOfNumbers > 0) {
double average = sum / amountOfNumbers;
System.out.printf("The smallest number is: %d.%n", smallestNumber);
System.out.printf("The largest number is: %d.%n", largestNumber);
System.out.printf("The average of all numbers is: %.4f.%n", average);
}
}
}
largestNumber is initialized to the smallest possible number so that it will be assigned the first entered number which must be larger than largestNumber.
Similarly, smallestNumber is initialized to the largest possible number.
If the first value entered is -99 then amountOfNumbers is zero and dividing by zero throws ArithmeticException (but maybe you haven't learned about exceptions yet). Hence, after the do-while loop, there is a check to see whether at least one number (that isn't -99) was entered.
You don't need to use printf to display the results. I'm just showing you that option.
I cannot figure out how to get the correct answer when averaging numbers and trying to "float it"(?) I am trying to get the answer to be 6.750, but only keep getting 6.000.
Instructions:
2.31 LAB: Simple statistics
Part 1
Given 4 integers, output their product and their average, using integer arithmetic.
Ex: If the input is:
8 10 5 4
the output is:
1600 6
Note: Integer division discards the fraction. Hence the average of 8 10 5 4 is output as 6, not 6.75.
Note: The test cases include four very large input values whose product results in overflow. You do not need to do anything special, but just observe that the output does not represent the correct product (in fact, four positive numbers yield a negative output; wow).
Submit the above for grading. Your program will fail the last test cases (which is expected), until you complete part 2 below.
Part 2
Also output the product and average, using floating-point arithmetic.
Output each floating-point value with three digits after the decimal point, which can be achieved as follows:
System.out.printf("%.3f", yourValue);
Ex: If the input is 8 10 5 4, the output is:
1600 6
1600.000 6.750
Here is my code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num1;
int num2;
int num3;
int num4;
int numAvg;
int numProd;
num1 = scnr.nextInt();
num2 = scnr.nextInt();
num3 = scnr.nextInt();
num4 = scnr.nextInt();
numAvg = ((num1 + num2 + num3 + num4) / 4);
numProd = num1 * num2 * num3 * num4;
System.out.println(numProd + " " + numAvg);
System.out.printf("%.3f", ((double) numProd));
System.out.print(" ");
System.out.printf("%.3f", ((double) numAvg));
}
}
`
This lab requires you to write 2 different calculations for each part, one for integer numbers and one for double numbers. Using large input for part 1 will cause an overflow before you print the result because you defined the product and average as integers.
//Part 1
int product = num1*num2*num3*num4;
int average = (num1+num2+num3+num4)/4;
System.out.println(product+" "+average);
//Part 2
double prod = ((double)num1)*num2*num3*num4;
double ave = (double)(num1+num2+num3+num4)/4;
System.out.printf("%.3f", prod);
System.out.print(" ");
System.out.printf("%.3f", ave);
System.out.println();
Below is a code I have written to give me the largest and smallest integer while also finding the average of the integers entered. My problem is that it is counting the negative number when finding the average. I need it to not count the negative number. Maybe subtracting one from the count? Or an if else statement?
import java.util.Scanner;
public class LargeSmallAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int smallest, largest, sum, count;
sum = 0;
count = 0;
System.out.println("Please enter a series of positive numbers. Enter a negative number to exit program.");
int positive = in.nextInt();
smallest = largest = positive;
while (positive > 0)
{
if (smallest > positive)
smallest = positive;
if (largest < positive)
largest = positive;
sum = sum + positive;
count++;
positive = in.nextInt();
}
double average = sum / count;
System.out.println("The smallest number entered was " + smallest);
System.out.println("The largest number entered was " + largest);
System.out.println("The average of all positive numbers entered is " + average);
}
}
OUTPUT:
Please enter a series of positive numbers. Enter a negative number to exit program.
2
20
10
5
10
2
-5
The smallest number entered was 2
The largest number entered was 20
The average of all positive numbers entered is 8.0
double average = ((double) sum) / count;
You used integer division 49 / 6 = 8.
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should: output the individual digits of 3456 as 3 4 5 6 and the sum as 18, output the individual digits of 8030 as 8 0 3 0 and the sum as 11, output the individual digits of 2345526 as 2 3 4 5 5 2 6 and the sum as 27, and output the individual digits of 4000 as 4 0 0 0 and the sum as 4.
Moreover, the computer always adds the digits in the positive direction even if the user enters a negative number. For example, output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the question I'm having minor difficulties with, the only part I can't figure out is how can I print the single integers in the order that he wants, from what I learned so far I can only print them in reverse. Here's my code:
import java.util.*;
public class assignment2Q1ForLoop {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
int usernum, remainder;
int counter, sum=0, N;
//Asaking the user to enter a limit so we can use a counter controlled loop
System.out.println("Please enter the number of digits of the integer");
N = console.nextInt();
System.out.println("Please enter your "+N+" digit number");
usernum = console.nextInt();
System.out.println("The individual numbers are:");
for(counter=0; counter < N; counter++) {
if(usernum<0)
usernum=-usernum;
remainder = usernum%10 ;
System.out.print(remainder+" ");
sum = sum+remainder ;
usernum = usernum/10;
}
System.out.println();
System.out.println("the sum of the individual digits is:"+sum);
}
}
You have to storeremainder variables in an array and then print them in the loop from last index to first as shown in this tutorial.
You can either store digits in array and then print them, or you can try something like that:
final Scanner console = new Scanner(System.in);
System.out.println("Please enter your number");
final int un = console.nextInt();
long n = un > 0 ? un : -un;
long d = 1;
while (n > d) d *= 10;
long s = 0;
System.out.println("The individual numbers are:");
while (d > 1) {
d /= 10;
final long t = n / d;
s += t;
System.out.print(t + " ");
n %= d;
}
System.out.println();
System.out.println("the sum of the individual digits is:" + s);
An idea would be : convert int to string and write a method
getChar(int index) : String
which gives you for example 4 from 3456 with
getChar(2);
See Java - Convert integer to string
Here, I wrote a code for your problem with using a stack. If you want a simple code, you can comment my solution and I will wrote another one.
Scanner c1 = new Scanner(System.in);
System.out.print("Enter the number: ");
int numb = c1.nextInt();
numb = Math.abs(numb);
Stack<Integer> digits = new Stack<Integer>();
while(numb>0){
int n = numb%10;
digits.push(n);
numb = numb/10;
}
int sum = 0;
while(!digits.isEmpty()){
int n = digits.pop();
sum+=n;
System.out.print(n+" ");
}
System.out.print(sum);
Today i tried to make a simple program in Java that gives me the average of the numbers i entered.
The problem is that if i use int added (as shown below), i don't get the same answer as when i use double added.
Code:
public class Main {
public static void main(String[] args) {
int amount;
int number;
int added = 0;
double average;
Scanner input = new Scanner(System.in);
System.out.println("This program calculates the average of the numbers entered by you.");
System.out.println("How many numbers do you want to enter?");
amount = input.nextInt();
for(int i=1; i<=amount; i++){
System.out.println("Enter a number:");
number = input.nextInt();
added = added + number;
}
average = added/amount;
System.out.println("The average of the numbers entered is: " + average);
}
}
Result:
This program calculates the average of the numbers entered by you.
How many numbers do you want to enter?
6
Enter a number:
3
Enter a number:
2
Enter a number:
4
Enter a number:
1
Enter a number:
6
Enter a number:
5
The average of the numbers entered is: 3.0
When i use double, i get the right answer:
public class Main {
public static void main(String[] args) {
int amount;
int number;
double added = 0;
double average;
Scanner input = new Scanner(System.in);
System.out.println("This program calculates the average of the numbers entered by you.");
System.out.println("How many numbers do you want to enter?");
amount = input.nextInt();
for(int i=1; i<=amount; i++){
System.out.println("Enter a number:");
number = input.nextInt();
added = added + number;
}
average = added/amount;
System.out.println("The average of the numbers entered is: " + average);
}
}
Result when i use double added instead of int added:
This program calculates the average of the numbers entered by you.
How many numbers do you want to enter?
6
Enter a number:
3
Enter a number:
2
Enter a number:
4
Enter a number:
1
Enter a number:
6
Enter a number:
5
The average of the numbers entered is: 3.5
Why does this happen and what should i do to avoid it?
To me it seems like added could be an int because i don't add up decimals but i add up whole numbers.
Thank you in advance.
In order for added/amount to return a non integer, either added or amount must be float or double or cast to either of them.
When both are int, an integer division takes place and the result is only converted to double after the division in order to be stored in your double average variable.
The result of a division in which both elements are integer, will be an integer. At least one of them needs to be a float or a double for the result of the division to be a floating point number.