I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.
How can I get the user input in Java?
I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.
How can I get the user input in Java?
This is a simple code that uses the
System.in.read()
function. This code just writes out whatever was typed. You can get rid of the while loop if you just want to take input once, and you could store answers in a character array if you so choose.You can make a simple program to ask for user's name and print what ever the reply use inputs.
Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.
So there you need Scanner class. You have to
import java.util.Scanner;
and in the code you need to useInput is a variable name.
See how this differs:
input.next();
,i = input.nextInt();
,d = input.nextDouble();
According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.
Also see the blog post "Scanner class and getting User Inputs".
You can get user input like this using a BufferedReader:
This is how you apply them
So when the user types in his name into the console, "String name" will store that information.
If it is a number you want to store, the code will look like this:
Hop this helps!