+ 7
Removing String (java)
Is there any possible way to remove the string? For example: String name = "1 + 1"; If( nam == 2){ //I want this like to act like this 👉 1+1 == 2; System.out.println("hello"); } Is there any way to change the data type from String to void? ___________________________________ I tried like this this but failed lol... 👇 void num = System.out.print("1+1"); And void num = System.out.print("1 " + " 1"); ______________________________________ Is that even possible by anyway? If so please tell me :) Thank you programmers! :)
14 Réponses
+ 5
Mr. 🍊range ,
As Avinesh said you can use switch but that'll not be enough to evaluate expressions in proper order.
In order to maintain proper evaluation order you need stack.
For example in 5+3*6 should be 23 not 48. Stack helps you to evaluate according to operator precedence.
I have used stack to evaluate postfix expression (oparands are digit only 0-9) . //but you need infix.
https://code.sololearn.com/cG9uKJ8aT7so/?ref=app
+ 5
👑 Prometheus 🇸🇬
To ask the user to type their question for example "3 + (8*3)" then calc their question...
I don't find any other way to solve my problem 😂 I know there a way to solve it... but I don't know how😂
+ 5
Avinesh
Yes that will work but...how do u convert arithmetic operations?
For example if they says
"40 - 3" how do u get that minus from the string?
+ 5
Mr. 🍊range , see this example by John sir. It does exactly what you asked.
https://code.sololearn.com/ctEXGtkw5ahO/?ref=app
+ 4
But why would you store a System.out.print()?
+ 4
Mr. 🍊range you can probably make use of switch case which can contain all the operators that can be mapped.
+ 3
🇮🇳Omkar🕉 since he mentioned only two operands separated by an operator I suggested him to go with switch directly.
But for more number of operands and operators, precedence comes into picture just like you said.
Nice example there👍
+ 2
Apart from using eval you can also use stack.
Just search for `infix expression evaluation using stack` on internet.
+ 2
For example
Scanner sc = new Scanner(System.in);
String name=sc.nextLine().replaceAll(“ “, “”);
int res=0;
if (name.contains(“+”)){
String[] arr = name.split(“+”);
for (int i=0; i<arr.length; i++{
int res+=Integer.parseInt(arr[i]);
}
}
System.out.println(res);
If user enter 32 + 6
you will replace all whitespaces
String name = “32+6”
arr[0]=32
arr[1]=6
res=38;
0
Take string input and convert them to integers for performing any operation.
0
I dont know what you are creating but you can try this code see if the format works for you.
int a = 1;
int b = 1;
String Name = Integer.toString(a+b);
int name = Integer.parseInt(Name);
if(name==2){
System.out.println("hello");
- 1
No removing
- 1
Int a=1;
Int c=1;
String name= int.toStrinh(a+b);
int name=int.parselnt(name);
if (name==2){
System.out.println("hello");