Is the program legal or not?
I am trying to correct out a statement that will print the value of 3 divided by 2.
I know this isn't correct.
System.out.print("The result is" + 3 / 2 + ".")
This is my answer.
System.out.print("The result is" + val + ".")
double val = 3 / 2
Is my answer correct or no? If not, how would I call upon the number?
You can do the following
double val = 3.0 / 2;
System.out.print("The result is" + val + ".");
the value val must be declared before it is printed. Also you need to make one of the number of type double so when the division is done, the answer is a double also. Else you lose precision.
the following is also valid:
double val = 3 / 2.0;
System.out.print("The result is" + val + ".");
if you do double val = 3 / 2; then 3/2 division is made with two integers which also give another integer. So 3/2 should give 1.5 but since we are only diving integers, it will omit the .5 and only give 1. Then 1 is casted as a double and becomes 1.0.
What you have is mostly correct:
float val1 = 3;
float val2 = 2;
float val= val1/val2;
System.out.println("The result is " + val + ".");
Remember your semicolons.
Also... You are correct to use a double (or float). Because otherwise your answer will be truncated.
EDIT:
Actually... I come to find that trying to do the operation in one shot still truncates the answer. It isn't correct unless both the values are set as floats. Then, run the math.
Here is proof: online java compiler
You need to declare first the variables. And if you want fraction numbers you need to do that with them. Need " ; " at the end of every statement. If you try it out in eclipse it will sign error to you when you don't write it where it need to be.
float num1 = 3;
float num2 = 2;
float val = num1 / num2;
System.out.print("The result is" + val + ".");
// Another way:
double num1 = 3;
double num2 = 2;
double val = num1 / num2;
System.out.print("The result is" + val + ".");
This should work:
double val = 3.0 / 2;
System.out.print("The result is" + val + ".");
Edit:
This is a case of integer division. When division is performed between two integers (here 3 and 2), the output is an integer and the fractional part gets trimmed off. So,3/2 will yield 1 which since you assign to a double variable, becomes 1.0.
When I do 3.0/2, 3.0 is a double value. The output here is a double value too i.e. 1.5; the fractional part is retained. Hence, my solution works.
Related
I am a beginner java programmer, studying off basic youtube videos and overflow forums, and i came across a question on an textbook sheet that asked me to use a for loop program and print this table out as well as fill in each blank
Number Square Cube (n+1)/(2n-18)
______________________________________
1 # # #
2 # # #
3 # # #
4 # # #
5 # # #
I thought I should try it out to test myself. I came up with the following program that works perfectly for the Number, Square and Cube part of the table, but I don't understand how to generate the numbers using the given formula. The formula I initialized as a variable (double) doesn't print the actual results, and I honestly don't have a clue as to what to do. I'd rather a simple explanation than a complex one and simple changes to the code rather than complex. As I said I am a beginner, and many different methods may go right over my head. Thank you so much in advance (also an extra task asks that I print out the sums of each column. I don't know how to do that at all, and would like an explanation if possible, but wouldn't mind if I don't receive one)
int number;
int maxValue;
Scanner keyboard = new Scanner(System.in);
System.out.println("how many numbers do you want the max value to be");
maxValue = keyboard.nextInt();
System.out.println("Number\tSquare\tCube (n+1)/(2n-18)");
System.out.println("--------------------------------");
for (number = 1; number <= maxValue; number++) {
double formula = (number + 1) / (number * 2);
System.out.println(
number + "\t\t\t" + number * number + "\t\t\t" +
number * number * number + "\t\t\t" + formula);
}
Your formula should be:
double formula = (double)(number + 1) / (number * 2 - 18);
Two issues:
missing -18
the / is doing an integer division unless you cast at least one operand into a double
Oh! one more thing: when number==9, there is a division by zero. A double division gives you "Infinity" whereas an integer division throws an exception.
Your formula does not match the textbook. Try this:
System.out.println("Number\tSquare\tCube (n+1)/(2n-18)");
System.out.println("--------------------------------");
for (int number=1; number <= maxValue; number++) {
double square = Math.pow(number, 2);
double cube = Math.pow(number, 3);
double formula = (number + 1) / (number * 2 - 18);
System.out.println(number + "\t\t\t" + square + "\t\t\t" + cube + "\t\t\t" + formula);
}
Note: As pointed out by #MauricePerry an input of 9 would cause a divide by zero. Rather than try to catch this unchecked exception, I think you should control your input values so that this does not happen.
Your formula is not correct and you are missing few \t.
int number;
int maxValue;
Scanner keyboard = new Scanner(System.in);
System.out.println("how many numbers do you want the max value to be");
maxValue = keyboard.nextInt();
System.out.println("Number\t\tSquare\t\tCube \t\t(n+1)/(2n-18)");
System.out.println("-------------------------------------------------------");
for (number = 1; number <= maxValue; number++) {
double formula = (number + 1) / (number * 2 - 18);
System.out
.println(number + "\t\t" + number * number + "\t\t" + number * number * number + "\t\t" + formula);
}
I'm not sure which outputs are you getting, but it seems to me you're using integer division when trying to get the result of (n+1)/(2n-18).
Try using:
double decimalNumber = (double) number;
double formula = (decimalNumber + 1) / (decimalNumber * 2 - 18);
Here is my code. For some reason my BMI is not calculated correctly.
When I check the output on a calculator for this : (10/((10/100)^2))) I get 1000, but in my program, I get 5. I'm not sure what I am doing wrong. Here is my code:
import javax.swing.*;
public class BMI {
public static void main(String args[]) {
int height;
int weight;
String getweight;
getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms");
String getheight;
getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters");
weight = Integer.parseInt(getweight);
height = Integer.parseInt(getheight);
double bmi;
bmi = (weight/((height/100)^2));
JOptionPane.showMessageDialog(null, "Your BMI is: " + bmi);
}
}
^ in java does not mean to raise to a power. It means XOR.
You can use java's Math.pow()
And you might want to consider using double instead of int—that is:
double height;
double weight;
Note that 199/100 evaluates to 1.
we can use
Math.pow(2, 4);
this mean 2 to the power 4 (2^4)
answer = 16
^ is not the operator you want. You are looking for the pow method of java.lang.Math.
You can use Math.pow(value, power).
Example:
Math.pow(23, 5); // 23 to the fifth power
Your calculation is likely the culprit. Try using:
bmi = weight / Math.pow(height / 100.0, 2.0);
Because both height and 100 are integers, you were likely getting the wrong answer when dividing. However, 100.0 is a double. I suggest you make weight a double as well. Also, the ^ operator is not for powers. Use the Math.pow() method instead.
Too late for the OP of course, but still...
Rearranging the expression as:
int bmi = (10000 * weight) / (height * height)
Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:
double bmi = (10000.0 * weight) / (height * height)
would still be an improvement.
You should use below method-
Math.pow(double a, double b)
From (https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#pow-double-double-)
Returns the value of the first argument raised to the power of the second argument.
int weight=10;
int height=10;
double bmi;
bmi = weight / Math.pow(height / 100.0, 2.0);
System.out.println("bmi"+(bmi));
double result = bmi * 100;
result = Math.round(result);
result = result / 100;
System.out.println("result"+result);
1) We usually do not use int data types to height, weight, distance,
temperature etc.(variables which can have decimal points)
Therefore height, weight should be double or float.
but double is more accurate than float when you have more decimal points
2) And instead of ^, you can change that calculation as below using Math.pow()
bmi = (weight/(Math.pow(height/100, 2)));
3) Math.pow() method has below definition
Math.pow(double var_1, double var_2);
Example:
i) Math.pow(8, 2) is produced 64 (8 to the power 2)
ii) Math.pow(8.2, 2.1) is produced 82.986813689753 (8.2 to the power 2.1)
I did the benchmarking with Math.pow(x,2) and x*x,
the result is that Math.pow() is easily forty times slower than manually multiplying it by itself, so i don't recommend it for anything where a little bit of performance is required.
Here's the results:
proof_of_work: 19.284756867003345
time for Math.pow(x,2) in ns: 35143
proof_of_work: 19.284756867003345
time for x*x in ns: 884
manual calculation is 39 times faster
and here's the test-code
double r1 = 4.391441320;
long multiply_d1 = System.nanoTime();
double multiply_dr = Math.pow(r1,2);
long multiply_d2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_dr));
System.out.println(("time for Math.pow(x,2) in ns: ") + (multiply_d2 - multiply_d1));
long multiply_t1 = System.nanoTime();
double multiply_tr = r1*r1;
long multiply_t2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_tr));
System.out.println(("time for x*x in ns: ") + (multiply_t2 - multiply_t1));
System.out.println(("manual calculation is ") + ((multiply_d2 - multiply_d1) / (multiply_t2 - multiply_t1)) + (" times faster"));
Most efficient solution is
public Float fastPow(Float number, Integer power) {
if (power == 0) {
return 1.0f;
} else if (power % 2 == 1) {
return fastPow(number, power - 1) * number;
} else {
return fastPow(number * number, power / 2);
}
}
Let A is our number and N our power. Then A^2^N = (A^2)^N. And A^N = (A^2)^N/2. The function above reflects this relationship.
I keep getting "syntax error on tokens please delete these tokens" on pretty much all of my System.out.println text after the first instance of System.out.println. I don't know what this means or how to fix it? I'm a very new beginning so there might be multiple mistakes in this code. I'm also getting "Syntax error on token ""doubled is"", invalid AssignmentOperator" and """squared is"", invalid AssignmentOperator" errors as well. This is an assignment for a class with the end result supposed to be
the opposite of n is y
n doubled is y
one-half of n is y
n squared is y
the reciprocal of n is y
one-tenth of n is y and y squared is z
n minus the last digit of n is y
the sum of n and n+1 and n+2 is y
Thank you!
import java.util.Scanner;
public class Arithmetic {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = scanner.nextInt();
int opposite = n*-1;
System.out.println("The opposite of" n "is" opposite);
int twoTimes = n*2;
System.out.println(n "doubled is" twoTimes);
int half = n/2;
System.out.println("half of "n "is" half);
int square= n*n;
System.out.println(n "squared is" square);
int reciprocal= 1/n;
System.out.println("the reciprocal of" n "is" reciprocal);
double fraction = n*.10;
double fractionTwo = fraction*fraction;
System.out.println("one-tenth of" n "is" fraction "and" fraction "squared is" fractionTwo);
// int lastDigit =
// System.out.println();
int sum= n+1;
int sumTwo= n+2;
int sumTotal= sum + sumTwo;
System.out.println("the sum of" n "and" sum "and" sumTwo "is" sumTotal);
}
}
**also if anybody would like to help me figure out the "n+1"/"n+2" formula and how to format that in code that would be appreciated!
There's a few mistakes with this code.
You're not concatenating correctly on any of your print to consoles.
System.out.println("The opposite of" n "is" opposite);
should be:
System.out.println("The opposite of" + n + "is" + opposite);
When we want to combine Strings we use the + sign.
int reciprocal= 1/n; will not work;
it should be double reciprocal= 1.0/n; assuming that n is an int.
"n+1"/"n+2" would simply be: double result = (n + 1.0) / (n + 2.0); assuming that n is an int.
That's not how you concatenate (link) two strings!
This code, and other similar ones,
System.out.println(n "doubled is" twoTimes);
are wrong.
I think you want to link n, "doubled is" and twoTimes together, right?
Right now you are linking them with spaces. But space characters in Java doesn't concatenate strings. So that's why the compiler complained.
In Java, + is both used to do addition and concatenation of strings! So you should change the above to:
System.out.println(n + "doubled is" + twoTimes);
But wait! Where have your spaces gone? This is because + doesn't automatically adds a space for you, you need to add it yourself.
System.out.println(n + " doubled is " + twoTimes);
Alternatively, you can use String.format to format your string. This
/* Explanation: n will be "inserted" to the first %d and twoTimes will
be inserted to the second %d. And %d basically means "express the thing in
decimal"*/
String.format("%d doubled is %d", n, twoTimes)
is the same as
n + " doubled is " + twoTimes
Regarding your formula question:
In Java, there are two different number types, int and double. (There are actually a lot more, but they're irrelevant) int and double do different things when they are divided. And they have different literals.
5 is an int literal, 5.0 is a double literal. See? Numbers without decimal places are ints and those with decimal places are called doubles.
So what's wrong with your formula? Let's first take a look at what the is the result of dividing int and double
int / int: 1 / 5 = 0
int / double: 1 / 5.0 = 0.2
double / int: 1.0 / 5 = 0.2
double / double: 1.0 / 5.0 = 0.2
int / 0: 1 / 0 = Exception!
double / 0: 1.0 / 0 = NaN
In your code:
int reciprocal= 1/n;
and other similar lines, you are doing division of int. So that's why the above code doesn't work. What you should do is change one of the numbers to a double! And also change the type to double.
double reciprocal = 1.0 / n;
------ ---
changes here as well!
How do I set a maximum length for a double?
double divSum = number1 / number2;
String divDisplay = number1 + " / " + number2 + " = " + divSum + " ";
JLabel divSumLabel= new JLabel();
divSumLabel.setText(divDisplay)
How do I set the maximum lenght for divSum?
1 / 3 = 0.333333... How do I set the maximum lenght, so its only 0.333?
I could do:
int maxLenght = 3;
String stringDivSum = String.valueOf(divSum);
String shortDivSum = null;
if(stringDivSum.length() > maxLenght){
shortDivSum = stringDivSum.substring(0, maxLenght);
}
String divDisplay = number1 + " / " + number2 + " = " + shortDivSum + " ";
But when I then do 1 / 3 it prints out 1 / 3 = 0.3?
Use String.format(...)
String.format()
double divSum = Double.parseDouble(String.format("%.3f",(double)number1 / number2)) ;
Precision, double.
We can specify the precision of a double or float. We use the "f" to
indicate a floating-point. Before this we specify ".3" to mean "three
numbers after the decimal."
double dblValue2 = Math.round( .333333 * 1000.0 ) / 1000.0;
this will help you
String.format("%.2f", (double)value);
You can try
System.out.format("%.2f + %.2f = %.2f",number1,number2,divsum)
You basically tell the formatter to expect 3 floats with 2 decimals with %.2f. It is important to supply the variables in order you want them to, so writing ,number1,number2,divsum will yield different results than writing ,number2,number1,divsum If you want to print int, short or long, you use %d. If you want to print string you use %s. But you can also google that.
Also, storing numeric data in String in case of mathematical operations is kind of pointless exercise and only bloats your code.
If you want to store the result of the division with a scale of 3 (i.e. 3 digits after the decimal point), you need to use a BigDecimal for this. This class allows to do arbitrary-precision calculus on decimal values.
int number1 = 1, number2 = 3;
BigDecimal divSum = BigDecimal.valueOf(number1).divide(BigDecimal.valueOf(number2), 3, RoundingMode.DOWN);
The divide(divisor, scale, roundingMode) function of BigDecimal can take a scale (here set to 3) and a rounding mode (here set to DOWN, this rounding mode truncates after the scale has been reached, which is what we want here). This will perform the division and the result will be rounded down with a scale of 3.
You can then print the result with:
String divDisplay = number1 + " / " + number2 + " = " + divSum + " ";
System.out.println(divDisplay); // prints "1 / 3 = 0.333"
I want to make sure that initializationg of the float variable resultd is correct. Since it is where the error lies.
static void caculateValues() {
int a, b;
int resulta, results, resultm;
float resultd;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a:");
a = sc.nextInt();
System.out.print("Enter b:");
b = sc.nextInt();
{
//This is the only part I edited//
resulta= a+b;
results=a-b;
resultm= a * b;
resultd= a / b;
//This is where I stopped editing//
}
System.out.println("The result of adding is " + resulta);
System.out.println("The result of subtracting is " + results);
System.out.println("The result of multiplying is " + resultm);
System.out.println("The result of dividing is " + resultd);
}
They claim my output should looks something like this:
(a = -50) (b = -20)
The result of adding is -70
The result of subtracting is -30
The result of multiplying is 1000
The result of dividing is 2.5
But supposedly my input shows:
The result of adding is -70
The result of subtracting is -30
The result of multiplying is 1000
The result of dividing is 2.0
Even if resultd is a float, you are still dividing two ints:
a / b
In Java, division of 2 ints must be an int. That is why 2.0 is showing up. -50 / -20 is 2, not 2.5 in Java. Only after the 2 is generated is it promoted to a float upon assignment to resultd.
Cast one of the variables to a float to force floating-point math from the start.
resultd = (float) a / b;
You could just as easily make resultd a double and cast a to a double instead.