0

I am a beiggner in java programming and i have a problem i want to get input from user in one line such as in c++
in c++ if i want to make a calculator i make 2 variable for example a band third is op and make user input them by

cin>>a>>op>>b;
if (op=='+')
{
    cout<<a+b<<endl;
}

and so on how to make that in Java ? i make a try in java but i get Error and one more question how to make user input a char i try char a=in.next(); but get error so i make it string
code java

Scanner in=new Scanner(System.in);
int a=in.nextInt();
String op=in.nextLine();
int b=in.nextInt();
if (op=="+")
{
    System.out.println(a+b);
}
else if  (op=="-")
{
    System.out.println(a-b);
}
 .........
user7179690
  • 868
  • 2
  • 11
  • 31
  • 1
    This might help you http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Konato_K Dec 07 '15 at 21:59
  • 1
    You can refer these posts: http://stackoverflow.com/questions/13942701/take-a-char-input-from-the-scanner AND http://stackoverflow.com/questions/4832933/performing-math-operation-when-operator-is-stored-in-a-string – The Guest Dec 07 '15 at 21:59
  • Thanks its helped me – user7179690 Dec 07 '15 at 22:06

1 Answers1

1

First of all, in Java you compare String with a.equals(b), in you example it would be op.equals("+"). And also, after reading a line it have the line break character (\n), so you should remove it to avoid problems. Remove it using String op = in.nextLine().replace("\n", "");.

And answering the how to read a character part, you can use char op = reader.next().charAt(0)

augustoccesar
  • 598
  • 7
  • 29