Reading a char from Scanner [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
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.
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);
}
}
Edited Version:
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);
}
}
First number:10.0
Operator:*
Second number:3.14
Answer: 31.400000000000002
Thanks a lot guys! Helped a lot!

Ok. This works and can help you on your road to java
public class Tester4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double num1, num2, answer = 0;
String operator;
System.out.println("Enter first number: ");
num1 = input.nextDouble();
System.out.println("Enter operator: ");
operator = input.next();
System.out.println("Enter second number: ");
num2 = input.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);
}
}

Use == in comparisons, not = (that means assignation).

As other have already pointed out, use the == operator to check for equality. The = operator will assign values instead.
In order to read a single character from the Scanner, take a look at the following question: Scanner method to get a char. There you'll find the suggestion to use Scanner.findInLine() method, which receives a regular expression as an argument. Providing the . wildcard character as pattern, you'll be able to get a String with the one next character, and using charAt(0) on it, you'll get it as a char.
Scanner sc = new Scanner("abc");
char ch = sc.findInLine(".").charAt(0);
System.out.println(ch); // prints "a"
Of course, you could also just use Scanner.next() to get the next word as a String, and just get its first character. But take into account that doing so would discard from the input buffer the rest of the word.

You need to use
if (operator == '+')
Notice the 'double equal to'.

Related

Average of numbers program outputting incorrect result

Am trying to write simple program to find average of 3 int values, but it always seems to get the average wrong
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num1 + num3)/3));
}
}
Help is greatly appreciate
Besides having num1 twice and missing num2, as already mentioned above, you will always get integer-results only, e.g. for num1 = 1, num2 = 2 and num3 = 2 your code will plot 1 as result instead of 1.667. You might enforce double-results in your output by writing
System.out.println("The average is:"+ ((num1 + num2 + num3) / 3.0));
It's supposed to be:
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num2 + num3)/3));
}
}
You accidentally added num1 twice, and forgot num2.

Simple Calculator: Addition wrong output [duplicate]

This question already has answers here:
Java printing a String containing an integer
(9 answers)
Closed 4 years ago.
I'm a beginner and I am trying to make a simple calculator in java. Everything works fine except for Addition has wrong output (e.g. 1+1 = 1.01.0). Here is a sample of my code
package Package;
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Equation:");
double num1 = input.nextDouble();
String oper = input.next();
String plus, minus, divide, modulus, multiply;
plus = "+";
minus = "-";
divide = "/";
multiply = "*";
modulus = "%";
//Everything is the same but addition seems to have wrong output
if (oper.equals(plus))
{
double num2 = input.nextDouble();
System.out.println("= " + num1 + num2);
}
else if (oper.equals(minus))
{
double num2 = input.nextDouble();
System.out.println(num1 - num2);
You are printing the Strings num1 and num2, not the result of the calculation.
When you print out a string ("=" in your case), Java will treat any number added to it as Strings as well).
To solve this, just add your calculation into parentheses to allow Java to calculate them separately:
System.out.println("=" + (num1 + num2));

Generating multiplication questions in Java

The code should output a table for Farenheit and Celsius
public static void main(String[] args) {
System.out.println("Fahrenheit\tCelsius");
System.out.println("=======================");
for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
{
System.out.printf("%5d |", temp);
double sum = (temp + (9.0/5.0)) * 32;
System.out.printf("%5d", (int)sum );
System.out.println();
You need to add a do while() loop to continue with the questions, for example:
static Scanner input;
static Scanner scanner;
static String question;
public static void main(String[] args) {
do {
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
input = new Scanner(System.in);
System.out.print("What is " + number1 + " * " + number2 + "? ");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect. Please try again. What is "
+ number1 + " * " + number2 + "? ");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct. Nice work!");
System.out.println("Want more questions yes or no? ");
scanner = new Scanner(System.in);
question = scanner.next();
}
} while (question.toLowerCase().equals("yes") ||
question.toLowerCase().equals("y"));
}
Simplest way would be do while loop. Example:
do{
// What you want to repeat and make sure to change have way to get out of loop like this:
System.out.print("Want more questions yes or no? ");
question = scanner.next();
}while(question.equals("yes") || question.equals("y"));
There's a few errors in your code but instead of giving you the entire solution to your homework problem I suggest you start with the simple case of reading input until the user enters 'n':
String input = "";
Scanner scanner = new Scanner(System. in);
while (!input.equals("n")) {
System.out.println("continue y/n?");
input = scanner.nextLine();
}
Add the generation of random ints, checking of answers etc inside the while loop body. Make sure to use equals instead of == when comparing two Strings

How can I read any user input from the scanner library?

I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!

How to recognize what math operation I am inputing? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am trying to make a simple calculator which can add, substract, divide and multiply any two numbers.
The way it works is that I ask for a number, then I ask for a sign (+,-,*,/) , and then I ask for the second number. The math should be done accordingly afterwards.
However I can't get the 'math sign' to be recognized properly by the program.
Here is my code:
package practice1;
import java.util.Scanner;
public class maiin {
public static void main(String[] args){
System.out.println("it works.");
double num1;
double num2;
String sign;
double total;
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
num1 = input.nextDouble();
System.out.println("Enter a +,-,/,* sign: ");
sign = input.nextLine();
input.nextLine();
System.out.println("Enter another number: ");
num2 = input.nextDouble();
if (sign.equals("+")){
total = num1 + num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("-")) {
total = num1 - num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("/")) {
total = num1 / num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("*")) {
total = num1 * num2;
System.out.println("Your total is: " + total);
} else {
System.out.println("Please enter the a proper sign");
}
When I run the program, I always get "Please enter the a proper sign".
Thank you in advanced.
I think you need to change
sign = input.nextLine();
input.nextLine();
to
sign = input.nextLine();
sign.nextLine();

Categories

Resources