using the command line prompt in Java Eclipse [duplicate] - 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?

One of the simplest ways is to use a Scanner object as follows:
import java.util.Scanner;
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();

You can use any of the following options based on the requirements.
Scanner class
import java.util.Scanner;
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
BufferedReader and InputStreamReader classes
import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);
DataInputStream class
import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader
Console class
import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Apparently, this method does not work well in some IDEs.

You can use the Scanner class or the Console class
Console console = System.console();
String input = console.readLine("Enter input:");

You can get user input using BufferedReader.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;
System.out.println("Enter your Account number: ");
accStr = br.readLine();
It will store a String value in accStr so you have to parse it to an int using Integer.parseInt.
int accInt = Integer.parseInt(accStr);

Here is how you can get the keyboard inputs:
Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");
String name = scanner.next(); // Get what the user types.

The best two options are BufferedReader and Scanner.
The most widely used method is Scanner and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.
Advantages of Using Scanner
Easy to use the Scanner class
Easy input of numbers (int, short, byte, float, long and double)
Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized, and specify or catch the exceptions.
Is able to read lines, white spaces, and regex-delimited tokens
Advantages of BufferedInputStream
BufferedInputStream is about reading in blocks of data rather than a single byte at a time
Can read chars, char arrays, and lines
Throws checked exceptions
Fast performance
Synchronized (you cannot share Scanner between threads)
Overall each input method has different purposes.
If you are inputting large amount of data BufferedReader might be
better for you
If you are inputting lots of numbers Scanner does automatic parsing
which is very convenient
For more basic uses I would recommend the Scanner because it is easier to use and easier to write programs with. Here is a quick example of how to create a Scanner. I will provide a comprehensive example below of how to use the Scanner
Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name"); // prompt user
name = scanner.next(); // get user input
(For more info about BufferedReader see How to use a BufferedReader and see Reading lines of Chars)
java.util.Scanner
import java.util.InputMismatchException; // import the exception catching class
import java.util.Scanner; // import the scanner class
public class RunScanner {
// main method which will run your program
public static void main(String args[]) {
// create your new scanner
// Note: since scanner is opened to "System.in" closing it will close "System.in".
// Do not close scanner until you no longer want to use it at all.
Scanner scanner = new Scanner(System.in);
// PROMPT THE USER
// Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
System.out.println("Please enter a number");
// use "try" to catch invalid inputs
try {
// get integer with "nextInt()"
int n = scanner.nextInt();
System.out.println("Please enter a decimal"); // PROMPT
// get decimal with "nextFloat()"
float f = scanner.nextFloat();
System.out.println("Please enter a word"); // PROMPT
// get single word with "next()"
String s = scanner.next();
// ---- Note: Scanner.nextInt() does not consume a nextLine character /n
// ---- In order to read a new line we first need to clear the current nextLine by reading it:
scanner.nextLine();
// ----
System.out.println("Please enter a line"); // PROMPT
// get line with "nextLine()"
String l = scanner.nextLine();
// do something with the input
System.out.println("The number entered was: " + n);
System.out.println("The decimal entered was: " + f);
System.out.println("The word entered was: " + s);
System.out.println("The line entered was: " + l);
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input entered. Please enter the specified input");
}
scanner.close(); // close the scanner so it doesn't leak
}
}
Note: Other classes such as Console and DataInputStream are also viable alternatives.
Console has some powerful features such as ability to read passwords, however, is not available in all IDE's (such as Eclipse). The reason this occurs is because Eclipse runs your application as a background process and not as a top-level process with a system console. Here is a link to a useful example on how to implement the Console class.
DataInputStream is primarily used for reading input as a primitive datatype, from an underlying input stream, in a machine-independent way. DataInputStream is usually used for reading binary data. It also provides convenience methods for reading certain data types. For example, it has a method to read a UTF String which can contain any number of lines within them.
However, it is a more complicated class and harder to implement so not recommended for beginners. Here is a link to a useful example how to implement a DataInputStream.

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 use
Scanner input = new Scanner(System.in);
Input is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
s = input.next(); // getting a String value
System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer
System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double
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".

To read a line or a string, you can use a BufferedReader object combined with an InputStreamReader one as follows:
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();

Here, the program asks the user to enter a number. After that, the program prints the digits of the number and the sum of the digits.
import java.util.Scanner;
public class PrintNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
int sum = 0;
System.out.println(
"Please enter a number to show its digits");
num = scan.nextInt();
System.out.println(
"Here are the digits and the sum of the digits");
while (num > 0) {
System.out.println("==>" + num % 10);
sum += num % 10;
num = num / 10;
}
System.out.println("Sum is " + sum);
}
}

Here is your program from the question using java.util.Scanner:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
int input = 0;
System.out.println("The super insano calculator");
System.out.println("enter the corrosponding number:");
Scanner reader3 = new Scanner(System.in);
System.out.println(
"1. Add | 2. Subtract | 3. Divide | 4. Multiply");
input = reader3.nextInt();
int a = 0, b = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
// get user input for a
a = reader.nextInt();
Scanner reader1 = new Scanner(System.in);
System.out.println("Enter the scend number");
// get user input for b
b = reader1.nextInt();
switch (input){
case 1: System.out.println(a + " + " + b + " = " + add(a, b));
break;
case 2: System.out.println(a + " - " + b + " = " + subtract(a, b));
break;
case 3: System.out.println(a + " / " + b + " = " + divide(a, b));
break;
case 4: System.out.println(a + " * " + b + " = " + multiply(a, b));
break;
default: System.out.println("your input is invalid!");
break;
}
}
static int add(int lhs, int rhs) { return lhs + rhs; }
static int subtract(int lhs, int rhs) { return lhs - rhs; }
static int divide(int lhs, int rhs) { return lhs / rhs; }
static int multiply(int lhs, int rhs) { return lhs * rhs; }
}

Scanner input = new Scanner(System.in);
String inputval = input.next();

Scanner input=new Scanner(System.in);
int integer=input.nextInt();
String string=input.next();
long longInteger=input.nextLong();

Just one extra detail. If you don't want to risk a memory/resource leak, you should close the scanner stream when you are finished:
myScanner.close();
Note that java 1.7 and later catch this as a compile warning (don't ask how I know that :-)

Here is a more developed version of the accepted answer that addresses two common needs:
Collecting user input repeatedly until an exit value has been entered
Dealing with invalid input values (non-integers in this example)
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter integers. Type 0 to exit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == 0) {
done = true;
}
else {
// do something with the input
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Please enter integers. Type 0 to exit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: 0
Exiting...
Note that without nextLine(), the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.

import java.util.Scanner;
class Daytwo{
public static void main(String[] args){
System.out.println("HelloWorld");
Scanner reader = new Scanner(System.in);
System.out.println("Enter the number ");
int n = reader.nextInt();
System.out.println("You entered " + n);
}
}

Add throws IOException beside main(), then
DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();

It is very simple to get input in java, all you have to do is:
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}

import java.util.Scanner;
public class Myapplication{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int a;
System.out.println("enter:");
a = in.nextInt();
System.out.println("Number is= " + a);
}
}

You can get user input like this using a BufferedReader:
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
// you will need to import these things.
This is how you apply them
String name = br.readline();
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:
int x = Integer.parseInt(br.readLine());
Hop this helps!

Can be something like this...
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int i = reader.nextInt();
for (int j = 0; j < i; j++)
System.out.println("I love java");
}

You can get the user input using Scanner. You can use the proper input validation using proper methods for different data types like next() for String or nextInt() for Integer.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
//reads the input until it reaches the space
System.out.println("Enter a string: ");
String str = scanner.next();
System.out.println("str = " + str);
//reads until the end of line
String aLine = scanner.nextLine();
//reads the integer
System.out.println("Enter an integer num: ");
int num = scanner.nextInt();
System.out.println("num = " + num);
//reads the double value
System.out.println("Enter a double: ");
double aDouble = scanner.nextDouble();
System.out.println("double = " + aDouble);
//reads the float value, long value, boolean value, byte and short
double aFloat = scanner.nextFloat();
long aLong = scanner.nextLong();
boolean aBoolean = scanner.nextBoolean();
byte aByte = scanner.nextByte();
short aShort = scanner.nextShort();
scanner.close();

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to the best program in the world! ");
while (true) {
System.out.print("Enter a query: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.equals("q")) {
System.out.println("The program is ending now ....");
break;
} else {
System.out.println("The program is running...");
}
}
}
}

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.
package main;
import java.io.IOException;
public class Root
{
public static void main(String[] args)
{
new Root();
}
public Root()
{
while(true)
{
try
{
for(int y = 0; y < System.in.available(); ++y)
{
System.out.print((char)System.in.read());
}
}
catch(IOException ex)
{
ex.printStackTrace(System.out);
break;
}
}
}
}

I like the following:
public String readLine(String tPromptString) {
byte[] tBuffer = new byte[256];
int tPos = 0;
System.out.print(tPromptString);
while(true) {
byte tNextByte = readByte();
if(tNextByte == 10) {
return new String(tBuffer, 0, tPos);
}
if(tNextByte != 13) {
tBuffer[tPos] = tNextByte;
++tPos;
}
}
}
and for example, I would do:
String name = this.readLine("What is your name?")

Keyboard entry using Scanner is possible, as others have posted. But in these highly graphic times it is pointless making a calculator without a graphical user interface (GUI).
In modern Java this means using a JavaFX drag-and-drop tool like Scene Builder to lay out a GUI that resembles a calculator's console.
Note that using Scene Builder is intuitively easy and demands no additional Java skill for its event handlers that what you already may have.
For user input, you should have a wide TextField at the top of the GUI console.
This is where the user enters the numbers that they want to perform functions on.
Below the TextField, you would have an array of function buttons doing basic (i.e. add/subtract/multiply/divide and memory/recall/clear) functions.
Once the GUI is lain out, you can then add the 'controller' references that link each button function to its Java implementation, e.g a call to method in your project's controller class.
This video is a bit old but still shows how easy Scene Builder is to use.

The most simple way to get user input would be to use Scanner. Here's an example of how it's supposed to be used:
import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();
The line of code import java.util.Scanner; tells the program that the programmer will be using user inputs in their code. Like it says, it imports the scanner utility. Scanner sc=new Scanner(System.in); tells the program to start the user inputs. After you do that, you must make a string or integer without a value, then put those in the line a=sc.nextInt(); or a=sc.nextLine();. This gives the variables the value of the user inputs. Then you can use it in your code. Hope this helps.

Using JOptionPane you can achieve it.
Int a =JOptionPane.showInputDialog(null,"Enter number:");

import java.util.Scanner;
public class userinput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Name : ");
String name = input.next();
System.out.print("Last Name : ");
String lname = input.next();
System.out.print("Age : ");
byte age = input.nextByte();
System.out.println(" " );
System.out.println(" " );
System.out.println("Firt Name: " + name);
System.out.println("Last Name: " + lname);
System.out.println(" Age: " + age);
}
}

class ex1 {
public static void main(String args[]){
int a, b, c;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = a + b;
System.out.println("c = " + c);
}
}
// Output
javac ex1.java
java ex1 10 20
c = 30

Related

Trying to stop a Do-While Loop for an application

I'm creating an application for a homework, the problem is that I am trying to create a do-while loop to exit the application (Using the question "Do you want to exit (Y/N)"). To work with the do-while loop, I created a method to store the app and then called the method in the do-while loop, so that when I try to stop the loop, the method loops once more. I want when I type "Y" to the console the whole program stops and doesn't loop one more time.
I created a simple example to explain my problem.
Here's the method:
public static void App(){
Scanner sc = new Scanner(System.in);
System.out.print("Write a number: ");
int num1 = sc.nextInt();
System.out.print("Write another number: ");
int num2 = sc.nextInt();
System.out.println("\nResult: "+(num1+num2));
}
And here I'm trying to create the loop in the main method:
public static void main(String[] args) {
Scanner sc2 = new Scanner(System.in);
App();
String answer;
do {
System.out.println("Do you want to exit (Y/N)?");
answer = sc2.next();
App();
} while (answer.equalsIgnoreCase("N")) ;
}
the problem is that I am trying to create a do-while loop to exit the application
You already have that in your program.
so that when I try to stop the loop, the method loops once more...
That doesn't fit the goal of your program.
I want when I type "Y" to the console the whole program stops and doesn't loop one more time
A lot of context that doesn't fit right in.
But anyway, you just have to reorganize your program.
In other words, just move your App() method.
public static void main(String[] args) {
Scanner sc2 = new Scanner(System.in);
String answer;
do {
App();
System.out.println("Do you want to exit (Y/N)?");
answer = sc2.next();
} while (answer.equalsIgnoreCase("N")) ;
}
Also, I spotted a lot of bad practices, so I kind of fixed them:
public static void main(String[] args) throws Exception {
try(Scanner sc2 = new Scanner(System.in)){
String answer;
do {
App();
System.out.print("Do you want to exit (Y/N)?");
answer = sc2.nextLine();
} while (answer.equalsIgnoreCase("N")) ;
}
}
Lastly, maybe (just maybe) try to solve your problem first before seeking help for your homework.
The reason why your program is running again after you type n is because the App() method is ran after the question is asked within the do part of the loop.
This code below is the simplest fix I could think of.
public static void main(String[] args) {
Scanner sc2 = new Scanner(System.in);
// I removed the line 'App();' as the App method will always run at least one time. Therefore putting that method within the 'do' part of the loop allows us to ask the user if they wish to exit or not after they have received their answer.
String answer;
do {
App();
System.out.print("Do you want to exit (Y/N)?"); //I changed the 'println' to 'print' here
answer = sc2.next();
} while (answer.equalsIgnoreCase("N")) ;
}
As a side note, methods in java should be lower-case when following typical Java naming conventions. While this will not affect how your code runs, I would suggest renaming the method from App() to app().
Everything looks good in your code, Just change the execution logic as shown in code blocks.
public static void main(String[] args) {
Scanner sc2 = new Scanner(System.in);
App(); //remove this line from here
String answer;
do {
App(); //call App function here so that it got executed at least one time
System.out.println("Do you want to exit (Y/N)?");
answer = sc2.next();
App(); //remove this as well
} while (answer.equalsIgnoreCase("N")) ;
}
Here is yet another approach except it uses a while loops instead of do/while loops. Two different approaches are provided and both provide User entry validation:
Approach #1:
public static void appMethod() {
Scanner sc = new Scanner(System.in);
int num1 = Integer.MIN_VALUE; // Initialize with some obscure value.
int num2 = Integer.MIN_VALUE; // Initialize with some obscure value.
while (num1 == Integer.MIN_VALUE) {
System.out.print("Write a number: ");
try {
num1 = sc.nextInt();
} catch ( java.util.InputMismatchException ex) {
System.out.println("Invalid Entry! Try again..."
+ System.lineSeparator());
sc.nextLine(); // consume the ENTER key hit otherwise this error will keep cycling.
num1 = Integer.MIN_VALUE;
}
}
while (num2 == Integer.MIN_VALUE) {
System.out.print("Now, write yet another number: ");
try {
num2 = sc.nextInt();
} catch ( java.util.InputMismatchException ex) {
System.out.println("Invalid Entry! Try again..."
+ System.lineSeparator());
sc.nextLine(); // consume the ENTER key hit otherwise this error will keep cycling.
num2 = Integer.MIN_VALUE;
}
}
System.out.println("\nResult: " + num1 +" + " + num2 + " = " + (num1 + num2));
}
Approach #2:
This next approach makes use of the Scanner#nextLine() method. The thing to remember about nextLine() is that, if you use it in your console application then basically recommend you use it for everything (all prompts). A 'quit' mechanism is also available in this version. Read the comments in code:
public static void appMethod() {
Scanner sc = new Scanner(System.in);
// Retrieve first number...
String num1 = "";
while (num1.isEmpty()) {
System.out.print("Write a number (q to quit): ");
// Making use of the Scanner#nextLine() method
num1 = sc.nextLine();
// Has 'q' been supplied to Quit?
if (num1.equalsIgnoreCase("q")) {
return;
}
/* Validate the fact that a signed or unsigned Integer or
Floating Point value has been entered. If not show Msg. */
if (!num1.matches("-?\\d+(\\.\\d+)?")) {
System.out.println("Invalid Entry! (" + num1 + ") Try again..."
+ System.lineSeparator());
num1 = ""; // empty num1 so as to re-loop.
}
}
// Retrieve second number...
String num2 = "";
while (num2.isEmpty()) {
System.out.print("Now, write yet another number (q to quit): ");
num2 = sc.nextLine();
if (num2.equalsIgnoreCase("q")) {
return;
}
if (!num2.matches("-?\\d+(\\.\\d+)?")) {
System.out.println("Invalid Entry! (" + num2 + ") Try again..."
+ System.lineSeparator());
num2 = "";
}
}
// Convert the numerical strings to double data type values.
double number1 = Double.parseDouble(num1);
double number2 = Double.parseDouble(num2);
// Display the result.
System.out.println("\nResult: " + num1 +" + " + num2 + " = " + (number1 + number2));
}

How to make a string equal a scanner and "if" statement?

I'm having a lot of trouble having the user input a string into the console and the specific string they typed equal an if statement. I want to input "SquareRoot" into the console and it go to the if statement, but when I type it in, nothing happens. What can I do to fix this? How do I make the user input equal to the string and the if statement? Is there something wrong with my "if" statement?
Scanner userInput = new Scanner(System.in);
String SquareRoot;
System.out.println("Type 'SquareRoot' - find the square root of (x)")
SquareRoot = userInput.next();
if(SquareRoot.equals("SquareRoot")) {
Scanner numInput = new Scanner(System.in);
System.out.println("Enter a number - ");
double sR;
sR = numInput.nextDouble();
System.out.println("The square root of " + sr + "is " + Math.sqrt(sR));
Your code was mostly correct:
You had some typos that would prevent your code compiling successfully. You
should consider using an IDE such as Eclipse, as it will highlight these
kinds of issues for you as you type.
You shouldn't create a 2nd Scanner object, reuse the existing one
Be sure to close your Scanner when done
Here's your corrected code:
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
String SquareRoot;
System.out.println("Type 'SquareRoot' - find the square root of (x)");
SquareRoot = userInput.next();
if (SquareRoot.equals("SquareRoot"))
{
// You shouldn't create a new Scanner
// Scanner numInput = new Scanner(System.in);
System.out.println("Enter a number - ");
double sR;
// Reuse the userInput Scanner
sR = userInput.nextDouble();
System.out.println("The square root of " + sR + " is " + Math.sqrt(sR));
}
// Be sure to close your Scanner when done
userInput.close();
}

How can I get multiple user inputs and save their value? [duplicate]

How could I read input from the console using the Scanner class? Something like this:
System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.
A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It's really quite simple.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
To retrieve a username I would probably use sc.nextLine().
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
You could also use next(String pattern) if you want more control over the input, or just validate the username variable.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();
Reading Data From The Console
BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.
readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n
Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace.
« Until the user enters data, the scanning operation may block, waiting for input.
« Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream.
« A scanner however is not thread safe. It has to be externally synchronized.
next() « Finds and returns the next complete token from this scanner.
nextInt() « Scans the next token of the input as an int.
Code
String name = null;
int number;
java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);
java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next(); // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);
// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
// Read a line from the user input. The cursor blinks after the specified input.
name = cnsl.readLine("Name: ");
System.out.println("Name entered: " + name);
}
Inputs and outputs of Stream
Reader Input: Output:
Yash 777 Line1 = Yash 777
7 Line1 = 7
Scanner Input: Output:
Yash 777 token1 = Yash
token2 = 777
There is problem with the input.nextInt() method - it only reads the int value.
So when reading the next line using input.nextLine() you receive "\n", i.e. the Enter key. So to skip this you have to add the input.nextLine().
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (it consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
There are several ways to get input from the user. Here in this program we will take the Scanner class to achieve the task. This Scanner class comes under java.util, hence the first line of the program is import java.util.Scanner; which allows the user to read values of various types in Java. The import statement line should have to be in the first line the java program, and we proceed further for code.
in.nextInt(); // It just reads the numbers
in.nextLine(); // It get the String which user enters
To access methods in the Scanner class create a new scanner object as "in". Now we use one of its method, that is "next". The "next" method gets the string of text that a user enters on the keyboard.
Here I'm using in.nextLine(); to get the String which the user enters.
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[]) {
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] arguments){
Scanner input = new Scanner(System.in);
String username;
double age;
String gender;
String marital_status;
int telephone_number;
// Allows a person to enter his/her name
Scanner one = new Scanner(System.in);
System.out.println("Enter Name:" );
username = one.next();
System.out.println("Name accepted " + username);
// Allows a person to enter his/her age
Scanner two = new Scanner(System.in);
System.out.println("Enter Age:" );
age = two.nextDouble();
System.out.println("Age accepted " + age);
// Allows a person to enter his/her gender
Scanner three = new Scanner(System.in);
System.out.println("Enter Gender:" );
gender = three.next();
System.out.println("Gender accepted " + gender);
// Allows a person to enter his/her marital status
Scanner four = new Scanner(System.in);
System.out.println("Enter Marital status:" );
marital_status = four.next();
System.out.println("Marital status accepted " + marital_status);
// Allows a person to enter his/her telephone number
Scanner five = new Scanner(System.in);
System.out.println("Enter Telephone number:" );
telephone_number = five.nextInt();
System.out.println("Telephone number accepted " + telephone_number);
}
}
You can make a simple program to ask for the user's name and print whatever the reply use inputs.
Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.
So there you need the Scanner class. You have to import java.util.Scanner;, and in the code you need to use:
Scanner input = new Scanner(System.in);
input is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value
System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer
System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double
See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();
According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.
A simple example:
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
int number1, number2, sum;
Scanner input = new Scanner(System.in);
System.out.println("Enter First multiple");
number1 = input.nextInt();
System.out.println("Enter second multiple");
number2 = input.nextInt();
sum = number1 * number2;
System.out.printf("The product of both number is %d", sum);
}
}
When the user enters his/her username, check for valid entry also.
java.util.Scanner input = new java.util.Scanner(System.in);
String userName;
final int validLength = 6; // This is the valid length of an user name
System.out.print("Please enter the username: ");
userName = input.nextLine();
while(userName.length() < validLength) {
// If the user enters less than validLength characters
// ask for entering again
System.out.println(
"\nUsername needs to be " + validLength + " character long");
System.out.print("\nPlease enter the username again: ");
userName = input.nextLine();
}
System.out.println("Username is: " + userName);
To read input:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
To read input when you call a method with some arguments/parameters:
if (args.length != 2) {
System.err.println("Utilizare: java Grep <fisier> <cuvant>");
System.exit(1);
}
try {
grep(args[0], args[1]);
} catch (IOException e) {
System.out.println(e.getMessage());
}
import java.util.*;
class Ss
{
int id, salary;
String name;
void Ss(int id, int salary, String name)
{
this.id = id;
this.salary = salary;
this.name = name;
}
void display()
{
System.out.println("The id of employee:" + id);
System.out.println("The name of employye:" + name);
System.out.println("The salary of employee:" + salary);
}
}
class employee
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
s.display();
}
}
Here is the complete class which performs the required operation:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int valid = 6;
Scanner one = new Scanner(System.in);
System.out.println("Enter your username: ");
String s = one.nextLine();
if (s.length() < valid) {
System.out.println("Enter a valid username");
System.out.println(
"User name must contain " + valid + " characters");
System.out.println("Enter again: ");
s = one.nextLine();
}
System.out.println("Username accepted: " + s);
Scanner two = new Scanner(System.in);
System.out.println("Enter your age: ");
int a = two.nextInt();
System.out.println("Age accepted: " + a);
Scanner three = new Scanner(System.in);
System.out.println("Enter your sex: ");
String sex = three.nextLine();
System.out.println("Sex accepted: " + sex);
}
}
There is a simple way to read from the console.
Please find the below code:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Reading of Integer
int number = sc.nextInt();
// Reading of String
String str = sc.next();
}
}
For a detailed understanding, please refer to the below documents.
Doc
Now let's talk about the detailed understanding of the Scanner class working:
public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}
This is the constructor for creating the Scanner instance.
Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
}
catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
By passing the System.in this code will opens the socket for reading from console.
You can flow this code:
Scanner obj= new Scanner(System.in);
String s = obj.nextLine();
You can use the Scanner class in Java
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);
import java.util.Scanner; // Import the Scanner class
class Main { // Main is the class name
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
you have wrote
Scanner = input()
this is wrong method, you have to make an integer or a string, i would like to prefer string, and then give a string any name that can be i that can be n or anything else, remember that you are giving name to username you can also give name username also, and the code is
String username = sc.nextline();
System.our.println("the username is" + username);
I hope you understand now

tantamount of while(cin>>something){some task ;} in java?

I'm a beginner in java. But I know that we have some trick for take input since user add input in c++.
while(cin>>x)
{
g++;
}
I want use from this in java ,thanks.
Use either command line arguments or the Scanner class.
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
You can put any loop in here. Search loops in java. And use this to perform what you're asking.

How to limit the input to the Scanner?

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = checkInput(in, "Enter an integer and a base: ");
int inputBase = checkInput(in, "");
}
public static int checkInput(Scanner in, String prompt) {
System.out.print(prompt);
while (!in.hasNextInt()) {
in.next();
System.out.println("Sorry, that is an invalid input.");
System.out.print(prompt);
}
return in.nextInt();
}
This method works and doesn't return any bad input i.e., ; p "hello".
My question is how can I limit the number of inputs the scanner will read. Say I input 5 five % ; but I only want 5 and five to be passed in to my method and the rest dropped.
I looked through the Java API but couldn't find a method that would limit the amount of user input accepted. Am I just missing it or is there another way to do this?
Edit: I have tried using the .length() method to limit the input but then that doesn't allow integers greater than the .length() parameter.
Here is a working sample of how you could accomplish what you need. I broke it up so that the user is prompted once for each input which makes it easier to validate. I changed your checkInput method to getInput which only returns valid user input as a String where it is then converted into an int.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = Integer.parseInt(getInput(in, "Enter an integer: "));
int inputBase = Integer.parseInt(getInput(in, "Enter a base: "));
System.out.println("Int: " + inputInt + ", base: " + inputBase);
}
public static String getInput(Scanner in, String prompt) { // Get valid user input
System.out.print(prompt); // Tell user what to input
String text = "";
while (true) { // Keep looping until valid input is found
text = in.nextLine(); // Get input from stdin
if(isInteger(text)) // Check if they put in integer
break; // Exit loop
System.out.print("Try again, " + prompt); // Wasn't valid, prompt again
}
return text; // Return valid user input
}
private static boolean isInteger(String str) { // Check if string is integer
try {
Integer.parseInt(str); // If this doesn't fail then it's integer
return true;
} catch(NumberFormatException e) {
return false; // Wasn't integer
}
}
Sample run:
Enter an integer: 2 dog five 3
Try again, Enter an integer: 2
Enter a base: cat
Try again, Enter a base: 3
Int: 2, base: 3
It helps to separate functionality - you were trying to read input, validate input, and convert to int all in one method. If you break it up it becomes easier to manage.
Scanner sc= new Scanner(System.in);
String string = sc.findInLine(".{500}"); // length of your input you want
findInLine(String pattern)
method of Scanner class of java.util package. This method returns a String object that satisfies the pattern specified as method argument.
see this article
If you want to only get the first two words (or strings delimited by spaces) you can use the str.split(" "); method.
For example:
String input = in.nextLine(); // Gets the next line the user enters (as a String)
String[] inputWords = input.split(" "); // inputWords[0] is first word, inputWords[1]
// is second word... etc
String validInput = inputWords[0] + " " + inputWords[1]; // Combines the first and
// second words into a string, so if you had "5 five %" validInput would be "5 five"
// inputWords[0] is "5", inputWords[1] is "five", inputWords[3] is "%" etc for any other words...
This will essentially limit the number of inputs to two words. I hope this helps!
Scanner scan = new Scanner(System.in);
System.out.println ("enter a 2 numbers");
String s;
s = scan.nextLine();
Scanner scan2 = new Scanner(s);
int one = scan2.nextInt();
int two = scan2.nextInt();
System.out.println (" int 1 = " + one + " int 2 = " + two);
enter a 2 numbers
23 45 68 96 45
int 1 = 23 int 2 = 45
Process completed.

Categories

Resources