Why do i get 10 2030 as the output? I can't figure out why it doesn' t output it as 10 50?
public class Testing1 {
public static void main(String args[]) {
int num1 = 10, num2 = 20, num3 = 30;
System.out.println(num1 + " " + num2 + num3);
This is because Java evaluates expressions with a 'precedence'. In this case, it starts at the left, and it works to the right, because the operations are all + they all have the same precedence so the left-to-right order is used. In the first 'addition', you add a number and a String. Java assumes the '+' is meant to do String concatenation, and you get the result "10 ". You then add that to 20, and get the (String concatenation) result "10 20". Finally you add the 30, again adding to a String, so you get the result"10 2030"`.
Note, if you change the order of your operations to:
System.out.println(num1+num2+" "+num3);
the num1+num2 will be treated as numbers, and will do numeric addition, giving the final result: "30 30"
To get the correct value you can change the evaluation order by making a sub-expression by using parenthesis (...) (which have a higher operator precedence than '+', and get the result with:
System.out.println(num1 + " " + (num2 + num3));
The num2 + num3 is evaluated first as a numeric expression, and only then is it incorporated as part of the string expression.
look up operator precedence and how + works when different types of operands
In java '+' operator operates differently for different operands.
For Integers operands it operates as integer addition
For strings it operates as concatenation.
Evaluation of java expression is based on precedence rule.In your case there is only '+' operator so evaluation is from left to right.
For integer and string operands java '+' operator performs string concatenation.
So num1 + " " + num2 + num3 execution is as
(integer + String) + int + int
(String + int)+ int
String + int
Your desired out put can be achieved by forcing the precedence for (num2 + num3) using parenthesis.
Related
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!
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.
This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 7 years ago.
I am trying to write a program in Java which takes input a String value
like s = "1+27-63*5/3+2" and returns the calculation in integer value
Here below is my code
package numberofcharacters;
import java.util.ArrayList;
public class App {
public static void main(String[] args) {
String toCalculate = "123+98-79÷2*5";
int operator_count = 0;
ArrayList<Character> operators = new ArrayList<>();
for (int i=0; i < toCalculate.length(); i++){
if (toCalculate.charAt(i) == '+' || toCalculate.charAt(i) == '-' ||
toCalculate.charAt(i) == '*' || toCalculate.charAt(i) == '÷' ) {
operator_count++; /*Calculating
number of operators in a String toCalculate
*/
operators.add(toCalculate.charAt(i)); /* Adding that operator to
ArrayList*/
}
}
System.out.println("");
System.out.println("Return Value :" );
String[] retval = toCalculate.split("\\+|\\-|\\*|\\÷", operator_count + 1);
int num1 = Integer.parseInt(retval[0]);
int num2 = 0;
int j = 0;
for (int i = 1; i < retval.length; i++) {
num2 = Integer.parseInt(retval[i]);
char operator = operators.get(j);
if (operator == '+') {
num1 = num1 + num2;
}else if(operator == '-'){
num1 = num1 - num2;
}else if(operator == '÷'){
num1 = num1 / num2;
}else{
num1 = num1 * num2;
}
j++;
}
System.out.println(num1); // Prints the result value
}
}
****The problem is I need to perform calculation according to Order of operations in Math like Multiplication and division first , than addition and subtraction.
How can I resolve this? ****
I have used String split() method to seperate the String wherever the operators "+-/*" occurs. I have used character ArrayList to add operators in it.
Than at the last portion of code I am looping in that splitted array of Strings and I've initialize int num1 with the first value of splitted array of strings by parsing it to Integer. and int num2 with the second value and the using operators arraylist to perform calculation between them (whatever the operator at that index of arraylist). and storing the result in int num1 and doing vice versa until the end of the string array.
[P.S] I tried to use Collection.sort but it sorts the above arraylist of operators in that order [*, +, -, /]. It puts division at the end while it should put division after or before multiplication symbol
If you want to do it with roughly the same structure of code, and not turn it into something like reverse Polish notation first, you could try an approach that deals with the operations in reverse priority order.
So assuming that you have * and / as highest precedence, and you're treating them as equal precedence and therefore to be dealt with left-to-right; and the same for + and -; then you would
Split first on + and -.
Evaluate the parts that are separated by + and -, but now processing * and / in left-to-right order.
Apply your + and - to these evaluated parts.
So if your expression is 3*4+5-6/2 then your code would split first into
3*4 + 5 - 6/2
Now evaluate these sub-expressions
12 + 5 - 3
Now process left-to-right to evaluate the final answer
14
In more general terms, the number of passes you'll need through your expression is determined by the number of precedence levels you have; and you need to process the precedence levels from lowest to highest. Split expression up; recursively evaluate sub-expressions just considering next precedence level and upwards; combine to get final answer.
This would be a nice little Java 8 streams exercise!
If I have the equation 7 + 13 = 20 as a string, how would I go about getting the operator symbol + out of the equation?
String operator = fileContent.substring(fileContent.indexOf('+'));
I tried something along these lines, as well as changing several things in it, but I have not been able to get the operator out. I've only been able to get it to return things like + 13 = 20 or 13 = 20 but never the operator alone.
I cannot use regex, try/catch, arrays, or SystemTokenizer for this.
Also, there will not always be spaces between the numbers, and they will not always be just one or two digits in size.
One last thing. I also need it so that if the operator were to be put into something like problem = (firstNumber + operator + secondNumber) it would actually work to compute the math.
The expected output, or at least what I'm trying to do, is to have it take the first and second number, and read the operator so that it can do the math of the problem. Its really confusing and I'm sorry.
int first = Integer.parseInt(fileContent.substring(0, fileContent.indexOf(" ")));
int second = secondNumber(result, fileContent);
int last = Integer.parseInt(result.substring(result.indexOf("=") + 1));
Here's the code I have to get the first, second, and the answer numbers, but I need to get the operator symbol out in a way that I can put it between the first and second numbers so that it will actually do the math, and so I can check it against the answer number.
Its for an assignment that will act as a "math problem grader" but none of the operators are the same.
I need it to take 7 and 13 and print 20 as the answer.
This answer will give the output +. Considering your variable name is operator, I assume that's what you want.
Using substring:
String operator = fileContent.substring(fileContent.indexOf('+'), fileContent.indexOf('+') + 1);
or written more readably:
int index = fileContent.indexOf('+');
String operator = fileContent.substring(index, index + 1);
Using charAt:
char operator = fileContent.charAt(fileContent.indexOf('+'));
or written more readably:
int index = fileContent.indexOf('+');
char operator = fileContent.charAt(index);
Edit:
Here is how to find the first and second numbers:
String eqn = "7 + 13 = 20";
int operatorIndex = eqn.indexOf(operator); // already defined operator as a String
int equalIndex = eqn.indexOf('=');
int first = Integer.parseInt(eqn.substring(0, operatorIndex).trim());
int second = Integer.parseInt(eqn.substring(operatorIndex + 1, equalIndex).trim());
Now we have String operator = "+"; and int first = 7; and int second = 13;
Click this sentence if you don't know what a switch statement is in Java. It's just a different way of using an if-structure. It's not difficult to understand. I can rewrite is using an if-structure if you need me too, though.
I would just use this:
String operator = "+";
int first = 7; int second = 13;
switch (operator)
{
case "+":
System.out.print("" + (first + second));
break;
case "-":
System.out.print("" + (first - second));
break;
case "*":
System.out.print("" + (first * second));
break;
case "/":
System.out.print("" + (first / second));
break;
default: System.out.print("not sum, difference, product or quotient");
}
In that case where operator = "+";, the output is 20. If operator = "-";, the output is -6.
Remove everything else:
String operator = fileContent.replaceAll("[^-+*/]", "");;
Note that the minus sign must come first or last in the character class or be escaped, otherwise it's a range operator.
I'm just starting out in AP Comp sci in high school and I stumbled across a question regarding the + operator in strings
Why does
System.out.println ("number" + 6 + 4 * 5)
result in number620
whereas
String s = "crunch";
int a = 3, b = 1;
System.out.print(s + a + b);
System.out.print(b + a + s);
result in crunch314crunch?
Thanks
Depends on It's precedence order
When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition (+).
If you want to do any Math into System.out.println, wrap it with braces, because Java sees String at 1st place.
Try System.out.println ("number" + (6 + 4 * 5)).
For 2nd example use: System.out.print(s + (a + b));
in this case you have sum of a and b.
but in System.out.print(b + a + s); b and a stay at the 1st place. Compiler does a+b 1st and after add String, you don't need braces
"*" has a higher operator precedence than "+", this means the expression "4 * 5" is calculated before the String concatenation happens.
See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
It has something to do with the operator precedence:
First, 4 * 5 = 20
Second, "number" is concatenated with 6, which is further concatenated with 20.
On your first example, since you used a multiplicative operator, 4 is being multiplied to 5 before concatenated to other string.
For the second example, you started with 2 integer before the String which will be calculated first before concatenated to a String.
Why does System.out.println ("number" + 6 + 4 * 5) result in number620
Because, * has higher precedence than +, so the result is number620.
String s = "crunch"; int a = 3, b = 1; System.out.print(s + a + b);
System.out.println(b + a + s); result in crunch314crunch?
Here, + is used as operator overloading not as binary operation. So, '+' do concat operation, not sum operation. So, the result is crunch314crunch.
It's about two things:
operator precedence
string concatenation vs addition
The + has the following rules:
int + int => int
int + string => String
String + int => String
String + String => String
That is, as soon as a String is involved, + means concatenation.
Operators with the same precedence are evaluated left to right. Therefore
String + int + int => String + int => String
but
int + int + String => int + String => String
The first case uses concatenation only, whereas the second uses addition in the first step.
In your first example, * has higher precedence than +, so the multiplication is performed first.
String + int * int => String + int => String
It's all about operator precedence and their associativity.
Your first example: "number" + 6 + 4 * 5
Acc. to operator precedence * is calculated first, so it becomes "number" + 6 + 20
Now, Associativity for + is Left -> Right (L->R), so + becomes a concatenation operator cause it is used with String, so the expression becomes "number6" + 20, and then "number620"
(Actually the int are converted to String before concatenation)
Similarly, your 2nd example:
Only + operator and start execution from L->R
"crunch" + 3 + 1 = "crunch3" + 1 = "crunch31"
1 + 3 + "crunch" = 4 + "crunch" = "4crunch"
According to your question and answer
explanation is
1.
A)System.out.println ("number" + 6 + 4 * 5);
B)System.out.println ("number6" + 4 * 5);
C)System.out.println ("number6" + 20);
D)System.out.println ("number620");
And it prints output like
number620
And Second one is
2.
A)System.out.print("crunch" + 3 + 1);
System.out.print(1 + 3 + "crunch");
B)System.out.print("crunch3" + 1);
System.out.print(4 + "crunch");
C)System.out.print("crunch31");
System.out.print("4crunch");
And it prints output with in a line, why because you have used print() statement
crunch314crunch