This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 4 years ago.
I am practicing a question: Type several numbers and stops while you type 0. Print out the maximum, minimum and average of the numbers you type.
Following is my code, and I was stuck in the calculation of average.
For example: when I type: 2 5 7 -1 0
the outcome is :
Type some numbers, and type 0 to end the calculattion:
2 5 7 -1 0
The numbers you type are:
2 5 7 -1
Sum is: 13
There are 4 numbers
The Max number is : 7
The minimum number is : -1
Average is : 3.0
However, the Average should be 3.25.
I've already made the variable avg in double type, why my output is still 3.0 rather than 3.25?
Thanks!!
public class Max_Min_Avg {
public static void main(String[] args) {
System.out.println("Type some numbers, and type 0 to end the calculattion: ");
Scanner scanner = new Scanner(System.in);
int numbs = scanner.nextInt();
int count =0;
int sum =0;
int max = 0;
int min=0;
System.out.println("The numbers you type are: ");
while(numbs!=0) {
System.out.print(numbs + " ");
sum += numbs;
count ++;
numbs = scanner.nextInt();
if(numbs>max) {
max = numbs;
}
if(numbs<min) {
min = numbs;
}
}
while(numbs ==0) {
break;
}
System.out.println();
double avg = (sum/count);
System.out.println("Sum is: "+ sum);
System.out.println("There are "+ count + " numbers");
System.out.println("The Max number is : " + max );
System.out.println("The minimum number is : " + min);
System.out.println("Average is : " + avg);
}
This is the issue of integer division .sum/count is calculated as int since sum and count is of type int. You can solve this by implicit casting.
Try :-
double avg = sum*1.0/count; // implicit casting.
Output :-
Type some numbers, and type 0 to end the calculattion:
2 5 7 -1 0
The numbers you type are:
2 5 7 -1
Sum is: 13
There are 4 numbers
The Max number is : 7
The minimum number is : -1
Average is : 3.25
Related
This question already has answers here:
Is there a method that calculates a factorial in Java? [closed]
(30 answers)
Closed 11 months ago.
im trying to implement a way to calculate facultys with for loops for a university project. I wrote a for loop that increases in steps of two, while another for loop calculates each faculty for the first for loop.
Can anybody point out where i made a mistake?
package Cosinus;
public class MainCos {
public static void main(String[] args) {
int fact=1;
for(int number = 0; number <= 10; number += 2) {
for(int i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("The Faculty of " + number + " is: " + fact);
}
}
}
I know it is hard for the first time, to figure factorial out, but basically, you need to multiply each number by the next integer so on.
There are many ways to solve it, one way you can create a method either recursively or iteratively. I would prefer iterator here a for loop perhaps.
n! factorial
You can also say it is n! or n factorial in general.
now S = 5! 1 * 2 * 3 * 4 * 5 = 120 in decimal.
long fact = 1;
for (long count = 2; count <= 10; count++) {
fact = fact * count;
System.out.println("The Faculty of " + count + " is: " + fact);
}
If you're trying to compute the factorial of the even numbers, then just move int fact=1; to between the for loops so that it gets reset for each new number:
for(int number = 0; number <= 10; number += 2) {
int fact=1;
for(int i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("The Faculty of " + number + " is: " + fact);
}
Output:
The Faculty of 0 is: 1
The Faculty of 2 is: 2
The Faculty of 4 is: 24
The Faculty of 6 is: 720
The Faculty of 8 is: 40320
The Faculty of 10 is: 3628800
As others have pointed out, though, there is no need for nested loops here. Another approach would be to use just the outer loop, incrementing by one, and only display the factorial for even numbers. I've also added in the base condition of 0! = 1 :
int fact=0;
for(int number = 0; number <= 10; number++) {
if (number == 0) {
fact = 1; // by definition
}
else {
fact = fact * number;
}
if (number % 2 == 0) {
System.out.println("The Faculty of " + number + " is: " + fact);
}
}
Producing the same output:
The Faculty of 0 is: 1
The Faculty of 2 is: 2
The Faculty of 4 is: 24
The Faculty of 6 is: 720
The Faculty of 8 is: 40320
The Faculty of 10 is: 3628800
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a task to add each numbers. One of my colleague helped me out and here's the code.
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
return sum;//write your code here
}
I'm not sure exactly how this works. Can someone please explain to me? Thanks.
You can use within while the loop which will accept any number as #GBlodgett suggested
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
while(number!=0)
{
sum = sum + number%10;
number = number/10;
}
return sum;//write your code here
}
In Java % is the modulo operator. It delivers the remainder of that division. If you divide integer values in Java, any remainder will be lost.
If you add some makeshift logging like that:
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
return sum; // write your code here
you will get the following output:
54
5
0
15
546 % 10 = 6
546 / 10 = 54
54 % 10 = 4
54 / 10 = 5
5 % 10 = 5
5 / 10 = 0
sum = 6 + 5 + 4 = 15
Your code will only work up to three digits. If you transfer the sequence of modulo and division operations into a loop it will be a generic solution.
The JVM(Java Virtual Machine) starts executing your code and public static void
main(String[] args) is the starting point.
Then executes System.out.println(sumDigitsInNumber(546));
System.out.println() is a method that prints the argument passed, into the System.out which is generally stdout (Standard output). The argument passed is the sumDigitsInNumber(546) method, hence it would print what sumDigitsInNumber() would return.
sumDigitsInNumber() initializes a sum variable with 0 to store the sum of 546.
sum = sum + number%10 gives you 6 (0 + 6), where number%10 gives
the last digit of 546 which is 6
number = number / 10 will replace number by 54 because 546/10 is 54.6 since it is an integer division .6 is ignored and 54 is stored in the number.
Repeat the above step twice but the number being 54 and then 5.
return sum returns the sum to the caller which is your main() method, hence System.out.println() printing the sum of 546.
Step by step:
this creates variable named sum and assigns it value of 0:
int sum = 0;
this does the following:
it assigns to variable 'sum' the result of sum + number % 10 (where a number is an argument passed to the method)
sum = sum + number%10;
number % 10 is in your example a remainder of 456 / 10, so in 456, you can pack number 10 exactly 45 times, whatever is left that is less then 10 is your result (remainder), in this case 6.
see http://www.cafeaulait.org/course/week2/15.html
next we divide current number by 10:
number = number / 10;
so 456 / 10 = 45.6
and as the type of variable is int - it is actually 45 (as int always rounds down the remainder) - see Int division: Why is the result of 1/3 == 0?
then it is being repeated 2 times until all 3 digits are summed up.
Notice, that your method will only work for 3 digit numbers. That's not that good.
You can easily make your method to work with any digits length int number passed.
Hint: use loops!
As you can see, you're repeating the same piece of code 3 times.
You could place it inside a loop and make it execute as many times as there are digits in your number.
something along these lines, but you need to figure out when to stop the while loop!
int sum = 0;
while (?WHEN TO EXIT?) {
sum = sum + number % 10;
number = number / 10;
}
Think about when you can exit loop (when, in example, maybe this number variable that you divide by 10 each iteration can tell you that all digits have been processed?)
Here is a solution that computes the sum of a number, no matter how many digits it has:
Generally speaking, a number has exactly [log(number)+1] digits, the tempInt variable is introduced to store the parameter value, it is considered a bad practice to modify the values of the method parameters :
public static int sumOfDigits(int number) {
int sum = 0;
int length = (int) Math.ceil(Math.log10(number));
int tempInt = number;
for (int i = 0; i < length; i++) {
sum += tempInt % 10;
tempInt /= 10;
}
return sum;
}
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10; // number%10 = the last digit of 546 (= 6), sum = 0 + 6
number = number/10; // number = number whithout the last digit (54)
sum = sum + number%10; // number%10 = the last digit of 54 (= 4), sum = 0 + 6 + 4
number = number/10; // number = number whithout the last digit (5)
sum = sum + number%10; // number%10= the last digit of 5 (= 5), sum = 0 + 6 + 4 + 5
number = number/10; // number = number whithout the last digit (useless)
return sum;//sum = 6 + 5 + 4 = 15
}
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);
Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4.
Design the program such it allows the user to re-run the
program with a different inputs in the same run.
public void findLargestInteger(){
//create Scanner object
Scanner input = new Scanner(System.in);
int x;
do {
//prompt user input
System.out.print("Enter an integer, the input ends if it is 0:");
//declare variables
int n, countNeg = 0, countPos = 0;
float sum = 0;
//calculate how many positive and negative values, total, and average
while ((n = input.nextInt()) != 0) {
sum = sum + n;
if (n > 0) {
countPos++;
}
else if (n < 0) {
countNeg++;
}
}
//display results
if (countPos + countNeg == 0) {
System.out.println("No numbers are entered except 0");
System.exit(0);
}
System.out.println("The number of positives is " + countPos);
System.out.println("The number of negatives is " + countNeg);
System.out.println("The total is " + sum);
System.out.println("The average is " + (sum / (countPos + countNeg)));
}while ((x = input.nextInt()) != 0);
}
How can I get the prompt to display correctly at the end and keep it
running?
Output:
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0 The average is 3.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0
The average is 3.0
You could change while((x = input.nextInt()) != 0); to while(true); if you really want to keep repeating your program.
That IS an infinite loop though which is not really a good way to go.
So instead of looking for the next integer and compare with 0, maybe you should write something like
System.out.print("Do you want to quit? (y/n): ");
at the end of your loop (right before the while((x = input.nextInt()) != 0) line).
And then not check for 0 but for the y. At least then you don't have the program waiting for the user to input something without knowing what's happening.
Edit: Or you can just use a counter if you want to run it like twice or three times before it terminates ;)
Have you tried just calling your function inside a while loop?
public void findLargestInteger() {
// Your code
}
public static void main(String[] args) {
do {
findLargestInteger();
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Would you like to continue? (0/1) ");
int n = reader.nextInt();
} while(n == 1);
}
I am compiling the code in command line with the following code typed in command line:
java aac 2 4 6 8 10
and I am getting the result:
5
The number in position 0 is 2.0
The Sum is: 2.0
The number in position 1 is 4.0
The Sum is: 4.0
The number in position 2 is 6.0
The Sum is: 6.0
The number in position 3 is 8.0
The Sum is: 8.0
The number in position 4 is 10.0
The Sum is: 10.0
What I am trying to achieve is, for the sum to be the total of all the numbers divided by the amount of numbers, however for the amount of numbers there is I have come up with a length variable. For this example the length is displayed as 5 right at the start.
public class aac {
public static void main(String args[]) {
// working out the length
int length = args.length;
System.out.println(length);
// this is a for loop that repeats until integer i is greater than
// integer length, which is the length of the args String array.
for (int i = 0; i < length; i++) {
// this string equals whatever value is in position i in string array args
String all = args[i];
// integer numConvert now equals the integer of String all
double numConvert = Double.parseDouble(all);
System.out.print("The number in position " + i + " is " + " ");
System.out.println(numConvert);
double sum = 0;
sum = sum += numConvert;
System.out.println("The Sum is: " + sum);
System.out.println();
}
}
}
Are you having problems creating the sum in order to calculate the average? If so, move the double sum = 0; out of your for loop. After the loop you divide it by args.length and that'll be your average.
Here's a little amelioration of your code :
double average = 0.0;
double sum = 0;
for(int i = 0; i < length; i++){
String all = args2[i];
double numConvert = Double.parseDouble(all);
System.out.print("The number in position "+i+" is ");
System.out.println(numConvert);
sum += numConvert;
average = sum / (i+1);
System.out.println("The Sum is: "+sum);
System.out.println("The average is :" + average);
System.out.println();
}
I created 2 double variables outside of your for loop.
Each time we loop in, the current value is added to the sum variable to get the total sum.
Also, the average is changed to the value of sum divided by the numbers we've already seen.
Here is the output :
5
The number in position 0 is 2.0
The Sum is: 2.0
The average is :2.0
The number in position 1 is 4.0
The Sum is: 6.0
The average is :3.0
The number in position 2 is 6.0
The Sum is: 12.0
The average is :4.0
The number in position 3 is 8.0
The Sum is: 20.0
The average is :5.0
The number in position 4 is 10.0
The Sum is: 30.0
The average is :6.0