Note that there are some explanatory texts on larger screens.

plurals
  1. POReading a char from Scanner
    primarykey
    data
    text
    <p>Sorry for the noob question. This is my first day trying out Java programming. I need help retrieving the users input of which operator the user wants to use with integers.</p> <pre><code>import java.util.Scanner; public class calculator { public static void main (String args[]) { Scanner number = new Scanner(System.in); double num1,num2,answer; char operator; System.out.println("Enter first number: "); num1 = number.nextDouble(); operator = number.nextChar(); /* the "nextChar" is not correct */ System.out.println("Enter second number: "); num2 = number.nextDouble(); if (operator = '+'){ answer = num1 + num2; /* If statements do not work like this */ } /* I would use "else if", unsure if it allows */ if (operator = '-'){ answer = num1 - num2; } if (operator = '*'){ answer = num1 - num2; } if (operator = '/'){ answer = num1 / num2; } System.out.println(num1 + num2 + operator + answer); } } </code></pre> <p>Edited Version:</p> <pre><code>import java.util.Scanner; public class calculator{ public static void main (String args[]) { Scanner userInput = new Scanner(System.in); String operator; double num1,num2,answer = 0; System.out.println("Enter first number: "); num1 = userInput.nextDouble(); System.out.println("Enter operator: "); operator = userInput.next(); System.out.println("Enter second number: "); num2 = userInput.nextDouble(); if (operator.equals ("+")){ answer = num1 + num2; } else if (operator.equals ("-")){ answer = num1 - num2; } else if (operator.equals ("*")){ answer = num1 * num2; } else if (operator.equals ("/")){ answer = num1 / num2; } System.out.println("First number:" + num1); System.out.println("Operator:" + operator); System.out.println("Second number:" + num2); System.out.println("Answer: " + answer); } } </code></pre> <blockquote> <p>First number:10.0</p> <p>Operator:*</p> <p>Second number:3.14</p> <p>Answer: 31.400000000000002</p> </blockquote> <p>Thanks a lot guys! Helped a lot!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload