Find the Average of digits by using While Loop - java

I know this is basis problem, but I just can't solve this, so I need your help..
I am trying to find the average of digits of the number(user input) by using While Loop, like for example, the average of digits of the number 789 is (7+8+9+)/3 = 8.
Could anyone help me with this..? Thank you so much.
import java.util.Scanner;
public class AVE
{
static int digits = 0;
static int average =0;
static int sum =0;
static int number;
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
System.out.println("what is your number?");
number = kb.nextInt();
avDigits();
System.out.println("The average is " + average);
}
public static void avDigits()
{
int num = number;
while (num > 0)
{
digits += 1;
sum += digits % 10;
num/=10;
}
average = (sum/digits);
}
}

Your issue is with the mod. You can rewrite the code as follows, Modification is done not only to correct the error but to make standardized. You need to change average to float or double.
import java.util.Scanner;
public class AVE {
public static void main(String[] args) {
int number;
float average = 0;
Scanner kb = new Scanner(System.in);
System.out.println("what is your number?");
number = kb.nextInt();
average = avDigits(number);
System.out.println("The average is " + average);
}
private static float avDigits(int number) {
int digits = 0;
float sum = 0.0F;
while (number > 0) {
digits += 1;
sum += number % 10;
number /= 10;
}
return (sum / digits);
}
}

You are taking mod of digits instead of num. Change the while loop as following:
while (num > 0)
{
digits += 1;
sum += num % 10; //<< Take mod of num here
num/=10;
}

import java.util.Scanner;
class AVE
{
static int digits = 0;
static float average =0;
static int sum =0;
static int number;
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
System.out.println("what is your number?");
number = kb.nextInt();
avDigits();
System.out.println("The average is " + average);
}
public static void avDigits()
{
int num = number;
while (num > 0)
{
digits += 1;
sum += num % 10; /*Do the modulo of num instead of digit. Since doing the modulo of num will give you the last digit*/
num/=10;
}
average = ((float)sum/digits); //average can be in decimal also
}
}

Related

Why is the first one cannot be executed?? and if i want to use the first one what should i add?? is it sum = (long) sum + n % 10; ? HELP MEEEEE

import java.util.Scanner;
public class Exercise33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
long n = input.nextLong();
System.out.println("The sum of the digits is: " + sumDigits(n));
}
public static long sumDigits(long n) {
int sum = 0;
while (n != 0) {
long sum = sum + n % 10;
n = n/10;
}
return sum;
}
}
import java.util.Scanner;
public class Exercise33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
long n = input.nextLong();
System.out.println("The sum of the digits is: " + sumDigits(n));
}
public static int sumDigits(long n) {
int sum = 0;
while (n != 0) {
sum += n % 10;
n /=10;
}
return sum;
}
}
Why is the first one cannot be executed?? and if i want to use the first one what should i add?? is it sum = (long) sum + n % 10; ? HELP MEEEEE
Take a look at
public static long sumDigits(long n) {
int sum = 0;
while (n != 0) {
long sum = sum + n % 10;
n = n/10;
}
return sum;
}
You have 2 variables named "sum" in the same scope.
int sum, long sum.
Why you have sum deklaret with int? The parameter from the sumDigits method has the datatype long. So change the datatype from sum in the methode from int to long. Then you must declare the sum in the while no more.
I hope this is what you searching for, otherwise you must ask your question more clearly where the problem is...
First Example:
public static long sumDigits(long n) {
long sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n/10;
}
return sum;
}

Varied amounts of input data

Problem: Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the average and max. A negative integer ends the input and is not included in the statistics.
Ex: When the input is:
15 20 0 5 -1
the output is:
10 20
You can assume that at least one non-negative integer is input.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.println(avg + " " + max);
}
}
I had a lot of trouble with this problem. Is there any way I could have done this without having to do count -1 while computing the average?
Also, is this this the most efficient way I could have done it?
How about this? If you have questions from the implementation, please ask.
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
int num = scnr.nextInt();
while (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
num = scnr.nextInt();
}
int avg = count == 0 ? 0 : total/count;
System.out.println(avg + " " + max);
}
If you use while loop instead of do-while loop, you don't have to count the negative number input anymore. And no, it's not the most efficient way, but it's a good start!
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userNum;
int maxNum = 0;
int totalSum = 0;
int averageNum;
int count = 0;
userNum = scnr.nextInt();
while (userNum >= 0) {
if (userNum > maxNum) {
maxNum = userNum;
}
totalSum += userNum;
++count;
userNum = scnr.nextInt();
}
averageNum = totalSum / count;
System.out.println("" + averageNum + " " + maxNum);
}
}
int Num;
int max = 0;
int total = 0;
int average;
int count = 0;
Num = scnr.nextInt();
while (Num >= 0) {
if (Num > max) {
max = Num;
}
total += Num;
++count;
Num = scnr.nextInt();
}
average = total / count;
System.out.println("" + average + " " + max);
}
}

Print double with two decimal problem in java

I have problem with similar task.
Here is the task:
The sample tests are:
This is my code:
import java.text.DecimalFormat;
import java.util.Scanner;
public class MinMaxSumAverage {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#0.00");
Scanner scanner = new Scanner(System.in);
double average;
double sum = 0;
double max = Integer.MIN_VALUE;
double min = Integer.MAX_VALUE;
double numbers = scanner.nextInt();
for (int i = 0; i < numbers; ++i) {
int num = scanner.nextInt();
if (num > max) max = num;
if (num < min) min = num;
sum += num;
}
average = sum / numbers;
System.out.println("min=" + (df.format(min)));
System.out.println("max=" + (df.format(max)));
System.out.println("sum=" + (df.format(sum)));
System.out.println("avg=" + (df.format(average)));
}
}
It work correct, but in "judge system" who test my code have some errors:
Can you help me to find what's wrong with my code?
Edit:
I change sum, max & min from double to int, and test result have minimal changes:
Test 2:
Your code is failing to accept decimal inputs that's why you are receiving InputMismatchException. Change this line
int num = scanner.nextInt();
to
double num = scanner.nextDouble();

How to sum powers of 2 with while loop

I need to calculate the sum of 2^0+2^1+2^2+...+2^n, where n is a number entered by the user. The main problem is that I don't know how to use the while loop to sum the different result of 2^n up.
Here is what I've tried:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(power <= i) {
Math.pow(number, i);
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + result);
}
}
Only you have to do is:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
double sum = Math.pow(2,power+ 1 ) - 1;
System.out.println("The sum is: " + sum);
}
}
In this link explains the math expresion
All fine, just a few changes.
Change the parts code to
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
/*Remove this --------> while(power <= i) {*/
while (i <= power) {//it should be this
/*Remove this -------> Math.pow(number, i);*/
sum = sum + Math.pow(number, i);
i = i + 1;
}
System.out.println("The sum is: " + sum);
Your conditional is backwards, it should read:
while (i <= power)
You compute the sum of powers, then completely ignore it, just printing out the result of 2^i. you should be printing out sum, something like:
while (i <= power) {
sum += Math.pow(number, i);
i++;
}
System.out.println("The sum is: " + sum);
For style points this won't handle a negative power, so you'll need to test for that.
Dont understand why do you want to loop in this case. You can do it like :
System.out.println("The sum is: "+(Math.pow(2, power+1)-1 ));
But if you really want to use loop try this :
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(i<=power) {
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + sum);
Here is a solution with comments to explain the logic. While loops need some kind of variable to control the number of iterations. That variable of course needs to be updated somewhere inside the loop.
You can compute the sum of the powers with the Math.pow() function, obviously. No import statement is needed to use it. I hope this helps. Good luck.
/* Scanner and variable to get and hold user input */
Scanner scan = new Scanner( System.in );
int userInput = 0;
/* Variable to hold the sum, initialized to 0.0 */
double sum = 0.0;
/* Prompt the user, and obtain the reply */
System.out.print( "Enter the exponent: ");
userInput = scan.nextInt();
/* The while loop and it's initialized counter */
int counter = 0;
while( counter <= userInput ){
/* Add each power to sum using Math.pow() */
sum = sum + Math.pow( 2, counter );
/* Watch the output as the loop runs */
System.out.println( "Sum: " + sum );
counter++; // Increment counter, so the loop exits properly
} // End while loop
public class SumofSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
String c = "123";
char d[] = c.toCharArray();
int a[] = new int[d.length + 1];
for (int i = 0; i < d.length; i++)
a[i] = d[i] - 48;
int r = 0;
for (int i = 0; i < c.length(); i++)
r = r + (int) Math.pow(a[i], a[i + 1]);
System.out.println(r);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int power=Integer.parseInt(reader.nextLine());
int number=2;
int i=0;
int result=0;
while (power>=i) {
result += (int)Math.pow(number, i);
i++;
}
System.out.println("The result is "+result);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
double power=Double.parseDouble(reader.nextLine());
int number=2;
int i=0;
double sum=0;
while (power>=i) {
sum=sum+Math.pow(number, i);
i++;
}
System.out.println("The sum is "+sum);
}

How to sum the digits of two integers?

How could I use the following method to sum the integers of two numbers in a separate method? I'm trying to teach myself how to use overloaded methods but this is starting to confuse me. Thanks!
public static void sumNUmber(){
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
System.out.println(sum);
public static void main(String[] args) throws ClassNotFoundException {
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
System.out.println(sumDigits(num));
}
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
output
Enter a number
234
9
You probably want to take your core algorithm and put it into a single function and then call it twice, once for each number. For example,
// Core algorithm.
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
public static void sumNumber() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int numA = in.nextInt();
System.out.println("Enter another number");
int numB = in.nextInt();
int totalDigits = sumDigits(numA) + sumDigits(numB);
System.out.println(totalDigits);
}
//Merry Xmas :D
public int sumNumbers(int num) {
int returnval;
if (num < 10) {
return num;
} else if (num < 100) {
returnval = Math.floor(num/10) + (num%10);
} else if (num < 1000) {
returnval = Math.floor(num/100) + Math.floor(num/10) + (num%10);
} //repeat as needed
return 0;
}

Categories