Reputation: 101
I am trying to create a calculator in Java. here is all my code:
import java.util.Scanner;
public class Calculator {
public static void main (String[] args) throws java.lang.Exception{
Calculator.Calculating();
}
public static void Calculating() {
String usersCalc;
Scanner userInput = new Scanner( System.in );
System.out.println("Enter your calculation: ");
usersCalc = userInput.next();
//splits when sees plus
String[] parts = usersCalc.split("+");
//everything left to splitter
String part1 = parts[0];
//everything right to splitter
String part2 = parts[1];
int result;
int answerOne = Integer.parseInt(part1);
int answerTwo = Integer.parseInt(part2);
switch (usersCalc){
case '+':
result = answerOne + answerTwo;
break;
case '-':
result = part1 - part2;
break;
case '/':
result = part1 / part2;
break;
case'*':
result = part1 * part2;
break;
}
}
}
I am trying to do it so that the user enters a string like "2+2" and then I split it on symbol and then put it through a switch statement and it calculates it for me. however the code still has errors which I can't resolve. any ideas?
errors
Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted
Upvotes: 0
Views: 1471
Reputation: 11
public class Calc extends MouseAdapter implements ActionListener
{
JButton[] b=new JButton[28];
static JTextField tf,tf2;
JFrame jf;
static double val1=0,val2=0,result=0;
static int operator=0,plus=1,minus=1,mul=1,div=1,rem=1,no=0,sqrt=0,hit=0,dot=0,pp=0,mp=0,mulp=0,divp=0,remp=0; //mp,pp,remp,mulp,divp all the used for operator Precedence
String str[]={"MC","MR","MS","M+","M-","<-","CE","C","+/-","sqrt","7","8","9","/","%","4","5","6","*","1/x","1","2","3","-","=","0",".","+"};
public Calc(String s)
{
jf=new JFrame(s);
JPanel p=new JPanel();
p.setBackground(new Color(213, 219, 255));
jf.add(p);
JMenuBar mb=new JMenuBar();
jf.setJMenuBar(mb);
JMenu view=new JMenu("View");
mb.add(view);
JMenu edit=new JMenu("Edit");
mb.add(edit);
JMenu help=new JMenu("Help");
mb.add(help);
JMenuItem viewHelp=new JMenuItem("View Help");
help.add(viewHelp);
JMenuItem about=new JMenuItem("About Us");
help.add(about);
mb.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
mb.setCursor(new Cursor(Cursor.HAND_CURSOR));
mb.setFont(new Font("Time_New_Roaman", 0, 11));
tf=new JTextField();
tf2=new JTextField();
tf.setBackground(new Color(242, 248, 255));
tf2.setBackground(new Color(242, 248, 255));
tf2.setBounds(10,10,190,20);
tf.setBounds(10,29,190,30);
tf.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(-1, 1, 1, 1),BorderFactory.createLineBorder(new Color(153,153,153))));
tf2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(1, 1, -1, 1),BorderFactory.createLineBorder(new Color(153,153,153))));
tf.setFont(new Font("Time_New_Roaman",0,20));
tf2.setFont(new Font("Time_New_Roaman",0,14));
tf.setHorizontalAlignment(tf.RIGHT);
tf2.setHorizontalAlignment(tf2.RIGHT);
p.add(tf);
p.add(tf2);
tf2.setCaretColor(Color.WHITE);
for(int i=0,x=10,y=32,h=27,w=34;i<str.length;i++)
{
int temp=0;
if(i==24)
h=62;
if(i==25)
{
w=73;
temp=39;
}
if(i%5==0)
{
y+=35;
x=10;
}
if(str[i]=="<-")
{
str[i]=""+(char)8592;
}if(str[i]=="sqrt")
{
str[i]="\u221A";
}if(str[i]=="+/-")
{
str[i]="\u00B1";
}
b[i]=new JButton(str[i]);
b[i].setFont(new Font("Arial",0,12));
if(str[i]=="1/x")
{b[i].setFont(new Font("Lucida Calligraphy",0, 12)); }
b[i].setBounds(x,y,w,h);
b[i].setMargin(new Insets(1,4,1,4));
if(str[i]==""+(char)8592||str[i]=="=")
{
b[i].setFont(new Font("Arial",1,20));
}
p.add(b[i]);
if(str[i]=="1"||str[i]=="2"||str[i]=="3"||str[i]=="4"||str[i]=="5"||str[i]=="6"||str[i]=="7"||str[i]=="8"||str[i]=="9"||str[i]=="0"||str[i]==".")
{
b[i].setBackground(new Color(234, 245, 248));
b[i].setFont(new Font("Arial",0,15));
}
b[i].addActionListener(this);
b[i].addMouseListener(this);
x+=39+temp;
h=27;
w=34;
}
p.setLayout(null);
Toolkit t=jf.getToolkit();
Dimension screensize=t.getScreenSize();
int width = screensize.width*8/10;
int height = screensize.height*8/10;
jf.setBounds(width/2,height/4,width,height);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(215,330);
jf.setResizable(false);
jf.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b[10]||e.getSource()==b[11]||e.getSource()==b[12]||e.getSource()==b[15]||e.getSource()==b[16]||e.getSource()==b[17]||e.getSource()==b[20]||e.getSource()==b[21]||e.getSource()==b[22]||e.getSource()==b[25])
{hit=1;sqrt=1;pp=1;mp=1;mulp=1;divp=1;remp=1;}
if(e.getSource()==b[0]) //For MC Button
{}
if(e.getSource()==b[1]) //For MR Button
{}
if(e.getSource()==b[2]) //For MS Button
{}
if(e.getSource()==b[3]) //For M+ Button
{}
if(e.getSource()==b[4]) //For M- Button
{}
if(e.getSource()==b[5]) //For Backspace Button
{
no=1;
String s=tf.getText();
tf.setText("");
for(int i=0;i<s.length()-1;i++)
{tf.setText(tf.getText()+s.charAt(i));}
if(s.length()-1==0)
tf.setText("0");
}
if(e.getSource()==b[6]) //For CE Button
{
dot=0;no=1;
tf.setText("0");
}
if(e.getSource()==b[7]) //For C Button
{
tf.setText("0");
tf2.setText("");
val1=0;val2=0;hit=0;sqrt=0;plus=1;minus=1;mul=1;div=1;rem=1;dot=0;pp=0;mp=0;mulp=0;divp=0;remp=0;no=1;
tf.setFont(new Font("Time_New_Roaman",0,20));
}
if(e.getSource()==b[8]) //For +/- Button
{}
if(e.getSource()==b[9]) //For Sqrt Button
{
dot=0;no=1;
tf2.setText("");
if(sqrt==1)
{
double t;
double num=Double.parseDouble(tf.getText());
double squareRoot = num/2;
do {
t = squareRoot;
squareRoot =(t+(num/t))/2;
}while((t-squareRoot)!=0);
tf2.setText("sqrt("+num+")");
tf.setText(""+squareRoot);
}
}
if(e.getSource()==b[10]) //For 7 Button
{
if(no==1)
{ tf.setText(""); }
tf.setText(tf.getText().concat("7"));
no=0;
}
if(e.getSource()==b[11]) //For 8 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("8"));
no=0;
}
if(e.getSource()==b[12]) //For 9 Button
{if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("9"));
no=0;
}
if(e.getSource()==b[13]) //For / Button
{
no=1;dot=0;
if(div==2 && divp==1)
{
tf2.setText(tf2.getText()+tf.getText()+"/");
serve();
minus=1;plus=1;mul=1;rem=1;
}
if(div==1 && divp==1)
{
div=2;
val1=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+"/");
operator=4;
tf.setText("");
}divp=0;
}
if(e.getSource()==b[14]) //For % Button
{
no=1;dot=0;
if(rem==1 && remp==1)
{
val2=Double.parseDouble(tf.getText());
tf2.setText(tf2.getText()+tf.getText()+"%");
result=(val1*val2)/100;
tf.setText(""+result);
plus=1;mul=1;div=1;minus=1;
}
remp=0;
}
if(e.getSource()==b[15]) //For 4 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("4"));
no=0;
}
if(e.getSource()==b[16]) //For 5 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("5"));
no=0;
}
if(e.getSource()==b[17]) //For 6 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("6"));
no=0;
}
if(e.getSource()==b[18]) //For * Button
{
no=1;dot=0;
if(mul==2 && mulp==1)
{
tf2.setText(tf2.getText()+tf.getText()+"*");
serve();
minus=1;plus=1;div=1;rem=1;
}
if(mul==1 && mulp==1)
{
mul=2;
val1=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+"*");
operator=3;
tf.setText("");
}mulp=0;
}
if(e.getSource()==b[19]) //For 1/x Button
{}
if(e.getSource()==b[20]) //For 1 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("1"));
no=0;
}
if(e.getSource()==b[21]) //For 2 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("2"));
no=0;
}
if(e.getSource()==b[22]) //For 3 Button
{
if(no==1)
tf.setText("");
tf.setText(tf.getText().concat("3"));
no=0;
}
if(e.getSource()==b[23]) //For - Button
{
no=1;dot=0;
if(minus==2 && mp==1)
{
tf2.setText(tf2.getText()+tf.getText()+"-");
serve();
plus=1;mul=1;div=1;rem=1;
}
if(minus==1 && mp==1)
{
minus=2;
val1=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+"-");
operator=2;
tf.setText("");
}mp=0;
}
if(e.getSource()==b[24]) //For = Button
{
no=1;dot=0;mp=1;mulp=1;pp=1;divp=1;remp=1;plus=1;minus=1;mul=1;div=1;rem=1;
if(hit==1)
{
val2=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+val2);
switch(operator)
{
case 1: result=val1+val2;
break;
case 2: result=val1-val2;
break;
case 3: result=val1*val2;
break;
case 4: result=val1/val2;
break;
default: result=0;
}
tf.setText(""+result);
tf2.setText("");
val1=0;
val2=0;
}
else
{tf.setText(""+result);}
}
if(e.getSource()==b[25]) //For 0 Button
{
//dot=0;
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("0"));
no=0;
}
if(e.getSource()==b[26]) //For dot (.) Button
{
if(no==1)
tf.setText("");
if(dot==0)
{
dot=1;
tf.setText(tf.getText().concat("."));
}
if(dot==1)
{tf.setText(tf.getText());}
no=0;
}
if(e.getSource()==b[27]) //For + Button
{
no=1;dot=0;
if(plus==2 && pp==1)
{
tf2.setText(tf2.getText()+tf.getText()+"+");
serve();
minus=1;mul=1;div=1;rem=1;
}
if(plus==1 && pp==1)
{
plus=2;
val1=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+"+");
operator=1;
tf.setText("");
}pp=0;
}
if(tf.getText()!="") // For converting Font When Text is out of range
{
int count=0,i;
String s=tf.getText();
char ch[]=s.toCharArray();
//double d=Double.parseDouble(tf.getText());
for(i=0;i<ch.length;i++)
{
//d/=10;
count++;
}
if(count>=15&&count<20)
{
tf.setFont(new Font("Time_New_Roaman",1,16));
}if(count>=20)
{
tf.setFont(new Font("Time_New_Roaman",1,14));
}
}
}
public void mouseEntered(MouseEvent me)
{
for(int i=0;i<b.length;i++)
{
if(me.getSource()==b[i])
{
b[i].setBackground(new Color(255,204,153));
}
}
}
public void mouseExited(MouseEvent me)
{
for(int i=0;i<b.length;i++)
{
if(me.getSource()==b[i])
{
b[i].setBackground(UIManager.getColor("control"));
if(me.getSource()==b[10]||me.getSource()==b[11]||me.getSource()==b[12]||me.getSource()==b[15]||me.getSource()==b[16]||me.getSource()==b[17]||me.getSource()==b[20]||me.getSource()==b[21]||me.getSource()==b[22]||me.getSource()==b[25]||me.getSource()==b[26])
{
b[i].setBackground(new Color(234, 245, 248));
}
}
}
}
void serve()
{
val2=Double.parseDouble(tf.getText());
if(operator==1)
{
result=val1+val2;
pp=0;mp=1;mulp=1;divp=1;remp=1;
}
else if(operator==2)
{
result=val1-val2;
mp=0;mulp=1;pp=1;divp=1;remp=1;
}
else if(operator==3)
{
result=val1*val2;
mulp=0;pp=1;mp=1;divp=1;remp=1;
}
else if(operator==4)
{
result=val1/val2;
mulp=1;pp=1;mp=1;divp=0;remp=1;
}
tf.setText("");
tf.setText(""+result);
val1=Double.parseDouble(tf.getText());
}
public static void main(String... args)
{
new Calc("PariGanak");
Timer time=new Timer();
time.schedule(new TimerTask(){
public void run()
{
tf.setText("0");
no=1;
}
},100);
}
}
Upvotes: -1
Reputation: 3540
This is a common task for java interview: "Calculate value from string expression"
Here is the algorithm (Pseudo):
Check that expression is valid
Build a thee structure with two types of nodes - math operation and number
Recursively calculate the result
Upvotes: 1
Reputation: 1036
Your error is propably because you try to compile with a version <1.7 (guessing from your error). To use String with switch you need at least 1.7.
That won't resolve all your problems as other answers mention it you use String in the switch and char for the cases.
Also even with the switch statement it wont work because in "usersCalc" is still the complete calculation (e.g. 2+2) and not just the "+"
Upvotes: 0
Reputation: 54672
split the string by checking all possible operators
String[] parts = usersCalc.split("[+,-,*,/]");
check if userCalc contains the operator and do the same like
if (usersCalc.contains("+"))
result = answerOne + answerTwo;
else if (usersCalc.contains("-"))
result = answerOne - answerTwo;
......
Upvotes: 0
Reputation: 13402
You code have many errors:
part1
and part2
instead of answerOne
and answerTwo
Integer
values.String
in the switch
and using char
for case statements
.You can use regex
for splitting the input. Then find the operator
and pass it to the switch-statement
.
import java.util.Scanner;
public class Calculator {
public static void main (String[] args) throws java.lang.Exception{
Calculator.Calculating();
}
public static void Calculating() {
String usersCalc;
Scanner userInput = new Scanner( System.in );
System.out.println("Enter your calculation: ");
usersCalc = userInput.next();
//splits when sees plus
String[] parts = usersCalc.split("[+-/*]");
char operator = usersCalc.contains("+") ? '+' : usersCalc.contains("-") ? '-' : usersCalc.contains("*") ? '*' : '/';
//everything left to splitter
String part1 = parts[0];
//everything right to splitter
String part2 = parts[1];
int result = -1;
int answerOne = Integer.parseInt(part1);
int answerTwo = Integer.parseInt(part2);
switch (operator){
case '+':
result = answerOne + answerTwo;
break;
case '-':
result = answerOne - answerTwo;
break;
case '/':
if (answerTwo == 0) {
System.out.println("Invalid input.");
return;
}
result = answerOne / answerTwo;
break;
case'*':
result = answerOne * answerTwo;
break;
}
System.out.println(result);
}
}
Upvotes: 0
Reputation: 187
Try with contains() to check if it's +
, -
, *
or /
. Then split it and calculate it.
Upvotes: 2