user7179690
user7179690

Reputation: 1133

Get input from user in one line without space in java

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);
}
 .........

Upvotes: 0

Views: 1521

Answers (1)

augustoccesar
augustoccesar

Reputation: 666

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)

Upvotes: 1

Related Questions