I have a problem which I am trying to solve. The work is like:
The user will input a number say 5 and the output will be
Output:
5 55 555 5555 55555
sum: 61725
Another example,
Input: 4
Output:
4 44 444 4444
sum: 4936
I have displayed the series but can't do the sum.
Scanner input = new Scanner(System.in);
System.out.print("Input: ");
int in = input.nextInt();
int sum = 0;
System.out.println("Output: ");
for(int i=1;i<=in;i++){
for(int j=0;j<i;j++){
System.out.print(in);
}
System.out.print(" ");
}
this will print the series. You can change the whole code, no problem. Just CAN'T use any builtin function like Math.pow() etc.
I was thinking of using :
for(int a=1;a<=in;a++){
f=f*10+in; sum+=f;
}
int in = ...
int sum = 0;
int term = in;
for (int i = 0; i < in; i++) {
sum += term;
term = 10 * term + in;
}
The point is that you can compute the series 4, 44, 444, ... by simple arithmetic and a loop.
But note that this will break for large values of in for two reasons.
Challenge: See if you can figure out what they are!
You can use String#repeat function and parse it to integer. At every loop you would have to append it to sum:
sum = sum + Integer.valueOf(("" + in).repeat(in));
Without using ANY build-in functions, we have to notice, that in the sum in appears in times, 10 * in - (in - 1) times and so on (sum = in * in + 10 * in * (in - 1) + ...), hence you can use the following loop:
int sum = 0;
int currentIn = in;
for(int i = 0; i < in; i++) {
sum = sum + (in - i) * currentIn;
currentIn = currentIn * 10;
}
System.out.println(sum);
Notice this does it with single loop.
isnt it rather simple?
Scanner input = new Scanner(System.in);
System.out.print("Input: ");
int in = input.nextInt();
int sum = 0;
int product=1;
System.out.println("Output: ");
for(int i=1;i<=in;i++){
for(int j=0,prod=in;j<i;j++){
System.out.print(in);
prod=(j>0)?(prod*10)+in:prod;
}
sum+=prod;
System.out.print(" ");
}
System.out.println("sum: "+sum);
Try the below implementation:
long sum = 0;
String num;
for(int i=1;i<=in;i++){
num = ""; //re-initialize number
for(int j=0;j<i;j++){
num += in; //keep track of every individual number
System.out.print(in);
}
System.out.print(" ");
//sum up each number after space
sum += Integer.parseInt(num);
}
System.out.print("sum: " + sum);
Related
I made a calculator that does multiple things (adding consecutive numbers, adding multiple numbers, etc) but I am having trouble making it so that the calculator can multiply multiple numbers. So far, I've basically copied the code that adds multiple numbers, but I can't figure out how to make it multiply instead of add.
Here is my code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String arg[])
{
int n;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to add up to: ");
n = s.nextInt();
System.out.println("you entered: " + n + "");
sum = addConsecutiveNumbers(n);
System.out.println("sum of 1 to "+n+" = "+sum);
//following code is sum of any numbers you entered from console
//store the numbers into an array
int num;
int sumOfNums=0;
System.out.print("Please enter how many numbers you want to sum: ");
num=s.nextInt();
System.out.println("you want to sum "+num+" numbers ");
sumOfNums = addNumbers(num);
System.out.println("sum of "+num+" numbers = "+sumOfNums);
}
//Define a method which add consecutive numbers based on user's input and return the sum of the numbers
private static int addConsecutiveNumbers (int number)
{
int sum = 0;
for (int i = 1; i <= number; i++)
{
sum = sum + i;
}
return sum;
}
//Define a method which add numbers based on user's input and return the sum of the numbers
private static int addNumbers (int num)
{
Scanner s = new Scanner(System.in);
int a[] = new int[num];
int sumOfNums = 0;
for(int k = 0; k < num; k++)
{
System.out.println("enter number "+(k+1)+":");
a[k] = s.nextInt();
System.out.println("The array of a[" + k + "] = " + a[k]);
}
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
return sumOfNums;
}
//below is the part of code that I am having trouble with.
public static int multiplyNumbers(int num)
{
int Area = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[num];
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
for(int l = 0; l < num; l++)
{
System.out.println("enter number "+(l+1)+":");
a[l] = s.nextInt();
System.out.println("The array of a[" + l + "] = " + a[l]);
}
return Area;
}
}
I see one thing right away; The way I see your code, the following two lines a redundant:
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
You should have already asked the user how many numbers they want to multiply, because it's passed in as a parameter. As for your actual problem, take a look at these lines from the addNumbers() method:
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
All you gotta do is copy that code in right before your return statement (return Area;). You'll need to tweak it a bit so instead of using the sumOfNums variable, it uses the Area variable, and instead of adding, it multiplies. This can be done like so:
for(int j = 0;j < num ; j++) //j also needs to start at 0, I think you may have made a mistake when writing the summing method
{
Area *= a[j];
}
You'll notice there's an issue with this algorithm though (almost didn't catch it myself). Area starts off with a value of 0, so 0 multiplied by any number will always still be 0. Simple fix; just manually set Area to the first value before the loop. Something like this:
Area = a[0];
for(int j = 1; j < num; j++)
{
sumOfNums += a[j];
}
Also notice I started the for loop at j = 1 this time. This is because I already started Area as a[0], so we don't want to multiply that number twice.
You don't need to store values in an array for multiplication similarly for addition you can directly update the final result
public static int multiplyNumbers(int num) {
int Area = 1;
Scanner s = new Scanner(System.in);
System.out.println("Please enter how many numbers you want to multiply:");
num = s.nextInt();
for (int l = 0; l < num; l++) {
System.out.println("enter number " + (l + 1) + ":");
int temp = s.nextInt();
Area *= temp;
System.out.println("The array of a[" + l + "] = " + temp);
}
return Area;
}
I'm very new to Java programming (2 weeks in) and currently am practicing arrays.
My code is as follows:
import java.util.Scanner;
public class LA2_2_1 {
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int x;
double avg;
double num = 0;
System.out.print("Enter the number of items: ");
x = scan.nextInt();
int [] numbers = new int [x];
double sum = 0;
sum = sum + num;
for (int index = 0; index < numbers.length; index++)
{
System.out.print("Enter the numbers: ");
num = scan.nextDouble();
sum = sum + num;
System.out.println(sum);
}
avg = sum/x;
System.out.println("The average is " + avg);
}
}
Output:
Enter the number of items: 10
Enter the numbers: 3.4 5 6 1 6.5 7.8 3.5 8.5 6.3 9.5
3.4
Enter the numbers: 8.4
Enter the numbers: 14.4
Enter the numbers: 15.4
Enter the numbers: 21.9
Enter the numbers: 29.7
Enter the numbers: 33.2
Enter the numbers: 41.7
Enter the numbers: 48.0
Enter the numbers: 57.5
The average is 5.75
My question is, how can I format the code so that I get "Enter the numbers" to appear only once? I just want the program to ask the user for the series of numbers they want to input. I do not want it to output multiple "Enter the numbers".
I think this may have to do with the output being within a for loop, but I am not too positive. I tried taking it out, and both the average and output for "Enter the numbers" turned to 0.0.
Any input would be helpful.
Thank you
Just change your for loop from
for (int index = 0; index < numbers.length; index++)
{
System.out.print("Enter the numbers: ");
num = scan.nextDouble();
sum = sum + num;
System.out.println(sum);
}
to
System.out.print("Enter the numbers: ");
for (int index = 0; index < numbers.length; index++)
{
num = scan.nextDouble();
sum = sum + num;
}
System.out.println(sum);
Well looking over your code every time your for loop runs it will print out the line
System.out.print("Enter the numbers: ");
For as many times as you set the amount of numbers, in this case 10.
In order to fix this you would want to add System.out.print("Enter the numbers: "); before the for loop.
it's simple just put input prompt statement outside for loop:
System.out.print("Enter the numbers: ");
for (int index = 0; index < numbers.length; index++)
{
num = scan.nextDouble();
sum = sum + num;
}
System.out.println(sum); // sum print statement outside loop to get total sum
Just moving the print statement outside the loop works. Please try this working link as well http://rextester.com/live/ZDRYM2149
class Rextester
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int x;
double avg;
double num = 0;
System.out.print("Enter the number of items: ");
x = scan.nextInt();
int [] numbers = new int [x];
double sum = 0;
sum = sum + num;
System.out.print("Enter the numbers: ");
for (int index = 0; index < numbers.length; index++)
{
num = scan.nextDouble();
sum = sum + num;
}
System.out.println("The sum is " + sum);
avg = sum/x;
System.out.println("The average is " + avg);
}
}
consider my answer if your really learning an array because in your code you didn't use your array
public static void main(String args[])
{
//sb object for getting the actual int
StringBuilder sb = new StringBuilder("");
Scanner scan = new Scanner(System.in);
int x;
//this is for the array element of numbers e.g. numbers[y]
int y=0;
double sum=0;
double avg;
System.out.print("Enter the number of items: ");
x = scan.nextInt();
//please add the scan.nextLine that is why you are getting
scan.nextLine();
double[] numbers=new double[x];
System.out.print("Enter the numbers followed by space:");
String numberEntered=scan.nextLine();
for(int i=0;i<numberEntered.length();++i)
{
//everytime loop iterate new sb with empty value is created
sb=new StringBuilder("");
while(i<numberEntered.length()&&numberEntered.charAt(i)!=' ')
{
//get the actual String integer not containing space
sb.append(numberEntered.charAt(i));
++i;
}
//convert the String actual integers to integer
numbers[y]=Double.parseDouble(sb.toString());
//increment y for the array element of numbers
++y;
}
//get the sum using foreach loop containing the array of numbers
for(double myNumbers:numbers)
{
sum+=myNumbers;
}
avg=sum/x;
System.out.println("The average is " + avg);
}
import java.util.*;
public class Main {
Scanner input = new Scanner (System.in);
int n = 0, tn = 0, time = 0;int sum=0;
int t = input.nextInt(); //no. of test cases
for (int i =0; i<t; i++)
{
n = input.nextInt();//no. of timings
for (int j = 0; j<n; j++)
{
tn = input.nextInt(); //individual time
sum=0;
sum+=tn;
sum*=2;
}
System.out.println(t+". "+sum);
}
}
}
My output
output I am supposed to get
Can anyone tell me where I went wrong?
1.) You are setting every time sum=0 while taking new input so you are losing the previous values hence last time
sum=30
sum= 30*2 = 60
so reset the sum=0 when you are done with your first case input
2.) You need to do the multiplication after you add-up all the values so simply do the multiplication when you have the sum of all individual time values
for (int i = 0; i < t; i++) {
n = input.nextInt();// no. of timings
for (int j = 0; j < n; j++) {
tn = input.nextInt(); // individual time
// add all values first
sum += tn;
}
// multiply the total of values with 2
System.out.println(i + ". " + (sum * 2));
// now set sum=0 for next case
sum = 0;
}
Test case Output :
2
3
10
20
30
2. 120 // output of first case
2
100
50
2. 300 // output of second case
I have in array with some doubles in them. I want to divide them, for example with an array that contains 6.0, 3.0 and 2,0 the result should be 1 (6/3/2). I wrote the following code:
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
for(int k = 0; k < division; k ++) {
double resultDivision = divisionArray[k] / divisionArray[k + 1];
}
System.out.println("Result: " + resultDivision);
but that doesn't seem to work. I get the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 I'm a complete java beginner. Could anyone help me out? Thanks
Your code has three issues.
resultDivision is defined within the scope of the for loop, so it's not visible afterwards, when you print the result.
With #1 fixed, you'll get an ArrayOutOfBounds exception because the second for loop tries to access divisionArray[k+1].
You don't check the arguments that the user gives you. What if a user specifies that it wants to divide -5 numbers? Your code will try to create an array with a length of -5, causing an Exception. Also, What if a user wants to divide by zero? Are you fine with that?
Here's a slightly better version:
Scanner input = new Scanner(System.in);
int division = 0;
do {
System.out.print("How many numbers do you want to divide? ");
division = input.nextInt();
} while (division <= 0);
double[] divisionArray = new double[division];
for (int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
if (divisionArray[i] == 0 && i>0) { // Remove this if you want to allow the user to divide by zero. Entering zero as the first argument is legal
System.out.println("Zero is an illegal argument, please enter a different number");
i--;
}
}
double resultDivision = divisionArray[0];
for (int k = 1; k < division; k++) {
resultDivision = resultDivision / divisionArray[k];
}
System.out.println("Result: " + resultDivision);
Good luck.
this should work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
//remember the first value and divide it trough the second,
//third, fourth and so on...
double result = divisionArray[0];
for(int k = 1; k < division; k ++) {
result = result / divisionArray[k];
}
System.out.println("Result: " + result);
}
What is not working is the sum part. Its not equaling the right number. Ex: user puts in 25 so the sum should be 75, but the program prints out 50.
My code:
import java.util.Scanner;
public class SumH4
{
public static void main(String[] args)
{
//define data
int x;
int sum;
//scanner is needed
Scanner sc = new Scanner(System.in);
//get user data and initialize variables
System.out.println("Please input a positive whole number.");
x = sc.nextInt();
sc.nextLine();
sc.close();
System.out.println();
sum = 0;
//do computation
for(int a = 0; a < x; a = a + 1)
{
if(a%5==0)
{
sum = sum + a;
}
}
//print results
System.out.println("Sum = " + sum);
}
}
You're not including the number itself that is input by the user. Simply change the for loop to the below so that the input x gets added:
for (int a = 0; a <= x; a = a + 1) {
Change
for(int a = 0; a < x; a = a + 1)
to
for(int a = 0; a <= x; a = a + 1)
At the moment you're not including 25, that only goes upto 24 i.e. a < x means "while a is less than x", then you want "while a is less than OR EQUAL TO x".
Your loop test should be <= (not <), also I suggest you define variables when you need them. Finally, you shouldn't close() a Scanner on System.in because that closes System.in and if you refactor your code you may cause yourself a lot of pain with that. So, I would change your method like
Scanner sc = new Scanner(System.in);
System.out.println("Please input a positive whole number.");
int x = sc.nextInt();
int sum = 0;
for (int a = 0; a <= x; a++) {
if (a % 5 == 0) {
sum += a;
}
}
// print results
System.out.println("Sum = " + sum);