Trying to multiply two numbers together using only addition - java

so I'm trying to make a very simple program but I think I am over thinking it. I want to multiply two numbers together without using multiplication, only addition. I know I will have to add X to itself Y times in order to achieve this, but the way my for-loop is now, it simply adds X to itself once and never again. I know that this algorithm is in the wrong place, but I am unsure where else to put it or what else to do. Any help would be appreciated!
import java.util.Scanner;
public class multiply {
public static void main(String[] args) {
int x = 0;
int y = 0;
int answer = 0;
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a value for x");
x = scan.nextInt();
System.out.println("Please enter a value for y");
y = scan.nextInt();
for(int i = 0; i < y; i++){
answer = x+x;
}
System.out.println(x + " multiplied by " + y + " equals " + answer);
}
}

This is incorrect
answer = x+x;
should be:
answer = x + answer;
or
answer += x

Your problem is that you are reassigning in each iteration of , you actually need to do like this
Try this
answer += x;

Related

How can I round down how many asterisks are printed in this code?

An assignment I am working on is asking me to modify a bar chart program they provided me with. So far I think I've got everything correct, although it specifies that "if a player has scored 48 points, then display four asterisks." However, my code displays five asterisks when a player has scored 48 points. How can I make it so that it only displays 4 asterisks? My instructor mentioned using integer division in my for loop which I did use, but that did not work.
import java.util.Scanner;
public class BarChart2 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int artPoints;
int bobPoints;
int calPoints;
int danPoints;
int eliPoints;
final int AMT_EACH_ASTERISK = 10;
System.out.println("Enter points earned for the season");
System.out.print(" by Art >> ");
artPoints = input.nextInt();
System.out.print(" by Bob >> ");
bobPoints = input.nextInt();
System.out.print(" by Cal >> ");
calPoints = input.nextInt();
System.out.print(" by Dan >> ");
danPoints = input.nextInt();
System.out.print(" by Eli >> ");
eliPoints = input.nextInt();
System.out.println("\nPoints for Season (each asterisk represents " +
AMT_EACH_ASTERISK + " points)\n");
drawChart("Art", artPoints, AMT_EACH_ASTERISK);
drawChart("Bob", bobPoints, AMT_EACH_ASTERISK);
drawChart("Cal", calPoints, AMT_EACH_ASTERISK);
drawChart("Dan", danPoints, AMT_EACH_ASTERISK);
drawChart("Eli", eliPoints, AMT_EACH_ASTERISK);
}
public static void drawChart(String name, int points, int amt_each) { // Main issue here
System.out.print(name + ": ");
int numAsterisks = points / amt_each;
for(numAsterisks = 0; numAsterisks < points; numAsterisks += amt_each)
System.out.print("*");
System.out.println();
}
}
Well, you're basically doing the correct calculation (integer division) here: int numAsterisks = points / amt_each; (this will result in 48/10 = 4).
However, you are then throwing that value away by reinitializing numAsterisks to 0 in your loop (for(numAsterisks = 0; ...)).
Instead do something like this:
for(int i= 0; i < numAsterisks; i++) {
System.out.print("*");
}
System.out.println();
Note that I added curly braces to the loop's body to make it clear what belongs into the loop and what doesn't. This is meant to prevent errors that could come from assuming that statements like System.out.println(); would be part of the body because of their indentation.

How do i overgo a misMatchExeption in an armstrongnumber calculation in Scanner?

I have written the following code, with following conditions. I was not allowed to use any String or Math class, so I used for loops, to break the number down.
It works for e.g 153 and 54883 but for numbers like 4679307774 the Scanner Type gives me back a misMatchExeption. I do understand why, I tried using long type, the program works then, but does not (due to Two`s) give back a correct answer.
I want to know, how to solve that problem, or better said what other things I could try here.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter any Integer above zero here : ");
System.out.println("Enter length of number, from 1 onwards: ");
int num = sc.nextInt();
int pow = sc.nextInt();
int narziss = 0; // TODO mismatchexeption
int single;
int a;
do {
a = 1;
single = num % 10; // takes each chiffre from behind, for as long as for runs.
System.out.println("single modulo : " + single);
num = num / 10;
for (int i = 0; i < pow; i++) {
a *= single;
System.out.println(a);
}
narziss += a;
System.out.println("narziss: " + narziss);
} while (num != 0);
System.out.println(" if the last shown number, " +
"is the same as you have typed in, " +
"you found an so-called armstrong number! ");
}
}
The problem i was asking, can be solved with a type other than Integer.
With long for example... or floating point types.
Be sure to change or cast all involved parts, like scanner, loops and so on.

How to print out an altered dynamic array

I think I have swapped the first and last numbers of a dynamic array with each other and am at a total loss as to how to print the array with the numbers swapped.
Ideally, with the program working, the user is supposed to enter in the number of numbers they want to enter and then they will type each number in individually. Then it is supposed to output (along with standard deviation, the mean, and the original array order) the array in order, except the first number entered and the last number entered are switched. How would you go about printing the new array with the switched numbers?
Here is my code so far:
import java.util.Scanner;
import java.lang.Math;
public class Project_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? ");
int N = scan.nextInt();
float sd, mean;
float Sum = 0;
float Square = 0;
float [] numbs = new float[N];
System.out.println("Enter your numbers below: ");
for (int i = 0; i < N; i++){
numbs[i] = scan.nextFloat();
Sum += numbs[i];
}
mean = Sum/N;
scan.close();
for (int j = 0; j < N; j++){
Square = (numbs[j] - mean) * (numbs[j] - mean);
}
sd = (float)Math.sqrt(Square/N);
System.out.println("The mean is: " + mean);
System.out.println("The standard deviation is: " + sd);
for (int k = 0; k < N; k++){
if (k == N-1){
System.out.print(numbs[k]);
}else{
System.out.print(numbs[k] + ", ");
}
}
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
}
}
You can swap the integers by doing the following,
int temp = numbs[N-1];
numbs[N-1] = numbs[0];
numbs[0] = temp;
Hope this helps :)
I did not realize that I would just have to enter another simple if statement to print it out. I was confused as to where the edited array was saving to, not realizing that it was just saving to the original array. Thank you all for the help.
In the end this is what I used for the code (in regards to my program specifically):
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
for (int g = 0; g < N; g++){
if (g == N-1){
System.out.print(numbs[g]);
}else{
System.out.print(numbs[g] + ", ");
}
Heres the output:
How many numbers would you like to enter? 5
Enter your numbers below:
1
2
3
4
5
The mean is: 3.0
The standard deviation is: 0.8944272
1.0, 2.0, 3.0, 4.0, 5.0
5.0, 2.0, 3.0, 4.0, 1.0

Java program gives incorrect Taylor series term for function e^x

//java program that asks the user to input a number that e^x=1+x+x^2/2! +x^3/3!... e is a mathematical constant equal to 2.718...
import java.util.Scanner;
public class taylor_2 {
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
double x; //input for x
double factorial=1; //initializes factorial
int counter=1; //initializes counter
double result=1; //initializes result
System.out.println("Enter non negative number"); //asks user to enter x
x=input.nextInt();
//output in while loop will continue to be generated if user doesn't entered a negative number
while(x<1){
System.out.println("I said entered a positive number");
x=input.nextInt();
}
while(x>counter){
factorial=factorial*counter;//factorial formula
result=result+(Math.pow(x,counter))/factorial; //equation for e^x=1+x+x^2/2! +x^3/3!
counter++;
}
System.out.println("Taylor series is " +result);//output for taylor equation e^x
}
}
Here is the output of my code:
Enter non negative number
2
Taylor series is 4.0
When I entered 2 , it should have outputted 7.3890560983 instead of 4.0 since e=2.718... and e^2=7.3890560983. What am I doing wrong?
The problem is that the Taylor series is not the same function that e^x.
It will return a function that is close to the function e^x.
For understanding it better, I recommend you to look the second picture of the next link:
https://en.wikipedia.org/wiki/Taylor_series
You can see in the previous picture that as n is getting larger the function is getting more accurate.
Your code's problem is that your x value is your n value, and this is not really true.
x: Must be the value you want to now e^x.
n: Is the accurate of your equation. Larger means more accurate.
So you must change while(x>counter) with while(n>counter), where n can be either a variable with the user selected accuracy, or a constant with your selected accurcy.
I think that until x=100, n=150 should work.
I hope that helps you! :)
There seems to be an answer here: EXP to Taylor series for c++, even though the algorithm is slightly different to yours. Here's its Java version:
public class TaylorSeries {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter x:");
double x = input.nextDouble();
double result = calcExp(x);
System.out.println("calcExp(x) = " + result);
System.out.println(" e^x = " + Math.pow(Math.E, x));
}
static double calcExp(double x) {
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
boolean negative = false;
int i = 1;
sum = 0.0;
if (x < 0) {
negative = true;
x = -x;
}
do {
sum += elem;
elem *= x / i;
i++;
if (sum > Double.MAX_VALUE) {
System.out.println("Too Large");
break;
}
}
while (elem >= eps);
return negative ? 1.0 / sum : sum;
}
}
The output:
Enter x:
2
calcExp(x) = 7.389056098930649
e^x = 7.3890560989306495
All credit should go to the answer here: EXP to Taylor series. I have only converted c++ code to Java

Java - Stuck in "for" loop

I am writing a java program that takes a number, x, as input from the user, sums all numbers from 1 to x (including x) that are divisible by 3, and displays the sum. it compiles without error but when I execute the program, it gets stuck in the loop and continues executing until I close the command prompt. I think the problem is inside the parenthesis after "for". I tried replacing the commands inside the loop with a simple
System.out.println("Hello");
and I got hundreds of Hello's streaming down the command prompt window. What am I doing wrong?
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number");
int x = keyboard.nextInt();
int i, total = 0;
for (i = 0; i <= x; i=+3)
{
total =+ i;
}
System.out.println("The sum is " + total);
}
Your =+ should be +=.
total =+ i; is the same as total = +i; which is the same as total = i;.
Your assignment is wrong. At the time being, you are simply assigning the counter to 3.
i += 3
You've done the same with your total variable as well. You can fix it in the same way:
total += i;
Wrong operator it is endlees loop. Use += not =+
i += 3
just fix when you increase the i and the total. Here is the class to compile and run :
import java.util.Scanner;
class keyboard {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number");
int x = keyboard.nextInt();
int i, total = 0;
for (i = 0; i <= x; i+=3)
{
total += i;
}
System.out.println("The sum is " + total);
}
}

Categories