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!
Related
How do I map numbers, linearly, between a and b to go between c and d.
That is, I want numbers between 2 and 6 to map to numbers between 10 and 20... but I need the generalized case.
My brain is fried.
If your number X falls between A and B, and you would like Y to fall between C and D, you can apply the following linear transform:
Y = (X-A)/(B-A) * (D-C) + C
That should give you what you want, although your question is a little ambiguous, since you could also map the interval in the reverse direction. Just watch out for division by zero and you should be OK.
Divide to get the ratio between the sizes of the two ranges, then subtract the starting value of your inital range, multiply by the ratio and add the starting value of your second range. In other words,
R = (20 - 10) / (6 - 2)
y = (x - 2) * R + 10
This evenly spreads the numbers from the first range in the second range.
It would be nice to have this functionality in the java.lang.Math class, as this is such a widely required function and is available in other languages.
Here is a simple implementation:
final static double EPSILON = 1e-12;
public static double map(double valueCoord1,
double startCoord1, double endCoord1,
double startCoord2, double endCoord2) {
if (Math.abs(endCoord1 - startCoord1) < EPSILON) {
throw new ArithmeticException("/ 0");
}
double offset = startCoord2;
double ratio = (endCoord2 - startCoord2) / (endCoord1 - startCoord1);
return ratio * (valueCoord1 - startCoord1) + offset;
}
I am putting this code here as a reference for future myself and may be it will help someone.
As an aside, this is the same problem as the classic convert celcius to farenheit where you want to map a number range that equates 0 - 100 (C) to 32 - 212 (F).
https://rosettacode.org/wiki/Map_range
[a1, a2] => [b1, b2]
if s in range of [a1, a2]
then t which will be in range of [b1, b2]
t= b1 + ((s- a1) * (b2-b1))/ (a2-a1)
In addition to #PeterAllenWebb answer, if you would like to reverse back the result use the following:
reverseX = (B-A)*(Y-C)/(D-C) + A
Each unit interval on the first range takes up (d-c)/(b-a) "space" on the second range.
Pseudo:
var interval = (d-c)/(b-a)
for n = 0 to (b - a)
print c + n*interval
How you handle the rounding is up to you.
if your range from [a to b] and you want to map it in [c to d] where x is the value you want to map
use this formula (linear mapping)
double R = (d-c)/(b-a)
double y = c+(x*R)+R
return(y)
Where X is the number to map from A-B to C-D, and Y is the result:
Take the linear interpolation formula, lerp(a,b,m)=a+(m*(b-a)), and put C and D in place of a and b to get Y=C+(m*(D-C)). Then, in place of m, put (X-A)/(B-A) to get Y=C+(((X-A)/(B-A))*(D-C)). This is an okay map function, but it can be simplified. Take the (D-C) piece, and put it inside the dividend to get Y=C+(((X-A)*(D-C))/(B-A)). This gives us another piece we can simplify, (X-A)*(D-C), which equates to (X*D)-(X*C)-(A*D)+(A*C). Pop that in, and you get Y=C+(((X*D)-(X*C)-(A*D)+(A*C))/(B-A)). The next thing you need to do is add in the +C bit. To do that, you multiply C by (B-A) to get ((B*C)-(A*C)), and move it into the dividend to get Y=(((X*D)-(X*C)-(A*D)+(A*C)+(B*C)-(A*C))/(B-A)). This is redundant, containing both a +(A*C) and a -(A*C), which cancel each other out. Remove them, and you get a final result of: Y=((X*D)-(X*C)-(A*D)+(B*C))/(B-A)
TL;DR: The standard map function, Y=C+(((X-A)/(B-A))*(D-C)), can be simplified down to Y=((X*D)-(X*C)-(A*D)+(B*C))/(B-A)
int srcMin = 2, srcMax = 6;
int tgtMin = 10, tgtMax = 20;
int nb = srcMax - srcMin;
int range = tgtMax - tgtMin;
float rate = (float) range / (float) nb;
println(srcMin + " > " + tgtMin);
float stepF = tgtMin;
for (int i = 1; i < nb; i++)
{
stepF += rate;
println((srcMin + i) + " > " + (int) (stepF + 0.5) + " (" + stepF + ")");
}
println(srcMax + " > " + tgtMax);
With checks on divide by zero, of course.
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);
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.
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.
Suppose in jdk 8 specification, and x1, x2 and y1, y2 are int variable, I want to know if following situations could happen:
mathematically x1/y1 != x2/y2 but in Java x1/(double)y1 == x2/(double)y2
mathematically x1/y1 == x2/y2 but in Java x1/(double)y1 != x2/(double)y2
Assuming mathematically 0/0 != 0/0 and Inf == Inf and +0 == -0
Ideally, you should specify a number system rather than the vague "mathematically". There are a lot of systems in mathematics that define division. I would have assumed you meant real number arithmetic, but it has a single zero and you seem to be permitting division by zero, which real number arithmetic does not define. I am going to assume you mean real number arithmetic for divisions not involving zero, extended in a way compatible with Java double arithmetic for divisions that do have a zero operand.
The first case can happen:
x1 = Integer.MAX_VALUE
y1 = Integer.MAX_VALUE-1
x2 = Integer.MAX_VALUE-1
y2 = Integer.MAX_VALUE-2
Both double divisions get the same answer: 1.0000000004656613
Clearly, the two divisions have different exact answers. The 40 decimal place BigDecimal results are:
1.0000000004656612877414201272105985574523
1.0000000004656612879582605622125704244886
Here is a demonstration program:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
double baseDouble = Integer.MAX_VALUE;
double minus1Double = Integer.MAX_VALUE - 1;
double minus2Double = Integer.MAX_VALUE - 2;
BigDecimal baseBD = new BigDecimal(Integer.MAX_VALUE);
BigDecimal minus1BD = new BigDecimal(Integer.MAX_VALUE - 1);
BigDecimal minus2BD = new BigDecimal(Integer.MAX_VALUE - 2);
System.out.println("base " + baseDouble + " " + baseBD);
System.out.println("minus1 " + minus1Double + " " + minus1BD);
System.out.println("minus2 " + minus2Double + " " + minus2BD);
System.out.println("Double base/minus1 " + baseDouble / minus1Double);
System.out.println("Double minus1/minus2 " + minus1Double / minus2Double);
System.out.println("BigDecimal base/minus1 "
+ baseBD.divide(minus1BD, 40, BigDecimal.ROUND_HALF_EVEN));
System.out.println("BigDecimal minus1/minus2 "
+ minus1BD.divide(minus2BD, 40, BigDecimal.ROUND_HALF_EVEN));
}
}
The output is:
base 2.147483647E9 2147483647
minus1 2.147483646E9 2147483646
minus2 2.147483645E9 2147483645
Double base/minus1 1.0000000004656613
Double minus1/minus2 1.0000000004656613
BigDecimal base/minus1 1.0000000004656612877414201272105985574523
BigDecimal minus1/minus2 1.0000000004656612879582605622125704244886
It is easy to see that the second case is impossible for divisions that do not have a zero operand.
Every int is exactly convertible to double, so the exact quotient of the doubles matches the exact quotient of the original values. For the definition of division, see the Java Language Specification, 15.17.2 Division Operator /. The process for dividing a pair of finite numbers neither of which is zero is equivalent to mapping the exact quotient into either the double value set or the double-extended-exponent value set.
Exponent overflow and underflow in double are impossible for the int range, so the two value sets will give the same answer. The rounding rules are independent of the calculation that led to the result being rounded, so two divisions of int-valued doubles that have the same exact quotient have the same rounded result.