I am working on an assignment which prompts the user to input an integer, and displays that integer with the digits separated by spaces, and provides the sum of those digits. I have this working, but my individual digit display is form the last digit to the first. How can I make it display the digits from first to last?
Here is what I have so far:
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
System.out.print(" " + temp + " ");
}while (num > 0);
System.out.println("The sum of the digits = " + sum);
}
}
One option would be to use the String#valueOf(Integer) method.
Example
int input = 12345;
String inputStr = String.valueOf(input);
for(char c : inputStr.toCharArray()) {
// Print out each letter.
}
if you use the method String.valueOf(12345)
you can easily reverse the String with the method in this library:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverse(java.lang.String)
StringUtils.reverse(String.valueOf(input));
Here is the solution
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
ArrayList<Integer> values = new ArrayList<>();
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
values.add(temp);
}while (num > 0);
Collections.reverse(values);
Iterator<Integer> it = values.iterator();
while(it.hasNext()){
System.out.println(" "+it.next()+" ");
}
System.out.println("The sum of the digits = " + sum);
}
}
BTW you should have to import ArrayList etc.
I would highly recommend putting the number into a String and then reading it, parsing it, and use the number however you want. As follows,
int input = 12345;
String inputString = input + "";
int sum = 0;
for (int i = 0; i < inputString.length(); i++) {
sum += Integer.parseInt(inputString.charAt(i) + "");
}
System.out.println(sum);
However an alternative way, not as pretty is..
int input = 12345;
int sum = 0;
while (input > 0) {
int i = (input + "").length() - 1;
int n = (int) (input / Math.pow(10, i));
input -= (int) (n * Math.pow(10, i));
sum += n;
}
System.out.println(sum);
Related
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);
}
}
You are given the sum 1 + (1+3)/2 + (1+3+5)/4 + … + (2.n-1)/ 2^(n-1). You should compile a program that (given integer N) finds and displays the value of the sum to the N-th addend.
I've written some code but I can't figure out the formula... Help?
Here is my code:
Scanner input = new Scanner(System.in);
System.out.print("n = ");
int n = input.nextInt();
double sum = 0;
for(int i = 1; i <= n; i++) {
sum = sum + (2 * i - 1) / (Math.pow(2, i - 1));
}
System.out.println(sum);
According to Pshemo's notice that 1+3+5+...+n = (n-1)^2 then your formula will be
And your code will be
Scanner input = new Scanner(System.in);
System.out.print("n = ");
int n = input.nextInt();
double sum = 0;
for(int i = 1; i <= n; i++) {
sum += 2 * Math.pow(i, 2) / Math.pow(2, i);
}
System.out.println(sum);
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);
}
Guys can you please help me answer this exercise using for loop without using string methods.
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,and output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the code:
package MyPackage;
import java.util.*;
public class Integer
{
public static void main(String args[])
{
Scanner console = new Scanner (System.in);
int input;
int sum = 0;
int num1 = 0;
int counter = 1;
String num = "";
System.out.print("enter a number: ");
input = console.nextInt();
if (input == (-input))
{
input = input * (-1);
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
}
else
{
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.err.println();
System.out.println("the sum is: " + sum);
}
}
}
Iterating all the digits from right to left is easy enough - you just keep dividing by 10 and keeping the remainder.
Since you need to print them from left to right, but there don't seem to be any constraint on the memory usage, you could just keep them in a list, and print it backwards:
int num = ...; // inputed from user
List<Integer> digits = new LinkedList<>();
int sum = 0;
// Extract the digits and the sum
while (num != 0) {
int digit = num % 10;
digits.add (digit);
sum += digit;
num /= 10;
}
// Print backwards:
System.out.print ("The digits are: ");
for (int i = digits.size() - 1; i >= 0; --i) {
System.out.print (digits.get(i) + " ");
}
System.out.println();
System.out.println("Their sum is: " + sum);
I need to do something like this - user types in a number (e.g. 5) and the program shows the result of the following action: 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 + 5*5*5.
My code is following:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt();
int a[] = new int[n];
int power = 0;
int sum = 0;
for (int i = 1; i <= a.length; i++)
{
power = (int) pow(i, 3);
// Maybe here'a the problem, a[n] has not enough space for the power (???)
sum += a[power];
}
System.out.println(Result: " + sum);
}
I think that I understand why this code doesn't work but I will appreciate any ideas about how to do it properly and runnable.
sum += power;, no need for a.
Or simply use math :
int n = input.nextInt();
int result = (int)(0.25 * Math.pow(n, 2)*Math.pow(1+n,2));
Or even more simple, as #ajb said :
int result = n*n*(n+1)*(n+1)/4;
Change:
sum += a[power];
to
a[i-1] = power;
sum += a[i-1];
or forget the array altogether
sum += power;
sum += a[power]; doesn't exist.
You need to :
store the power value in the ith array item.
add the ith array value to the sum
Change your loop body to:
power = (int) pow(i, 3);
a[i - 1] = power;
sum += a[i - 1];
You're doing way too much work.
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
sum = 1;
for (int i=2; i<=n; i++) {
sum += (int) Math.pow(i,3);
}
done. sum now contains the sum 1³ + 2³ + 3³ + ...
Or, more efficiently with exactly the same functionality:
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
sum = 1;
while(n > 1) {
sum += (int) Math.pow(n--,3);
}
Why? Because 1 + 5³ + 4³ + 3³ + 2³ is the same as 1³ + 2³ + 3³ + 4³ + 5³
Of course you could also just directly compute that value, using actual maths, cutting all the entire algorithm with a simple arithmetic oneliner.