Java: Read from console [duplicate] - java

This question already has answers here:
Getting Keyboard Input
(10 answers)
Closed 8 years ago.
I'm don't know how to read from the console in Java.
If it's possible I want to do it using a scanner.
This is what i tried while learning Java.
package Scanners;
import java.util.Scanner;
public class ConsoleScanner {
static Scanner input = new Scanner(System.in);
public static void main(String[] args){
if(input.equals("Hello"))
System.out.println("You typed in: Hello ");
if(input.equals("Good Bye"))
System.out.println("You typed in: Good Bye");
else{
System.out.println("You typed in: " + input);
}
}
}
It give's me this error:
You typed in:
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=false][need input=false][source
closed=false][skipped=false][group separator=.][decimal
separator=\,][positive prefix=][negative prefix=\Q-\E][positive
suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
If there is a better way to read from the console then please post it.
- Thanks

You don't want to print the Scanner itself. You want to call the various Scanner functions to get the input. Have a look at the Scanner API and the Scanner tutorial (which are the first and second results for googling "Java Scanner") for more info.

Try this:
package Scanners;
import java.util.Scanner;
public class ConsoleScanner {
static Scanner scanner = new Scanner(System.in); //Creates the scanner
public static void main(String[] args){
String input = scanner.NextLine(); //Sets the string input equal to whatever the user types next
if(input.equals("Hello"))
System.out.println("You typed in: Hello ");
if(input.equals("Good Bye"))
System.out.println("You typed in: Good Bye");
else{
System.out.println("You typed in: " + input);
}
}
}

My friend you have to use
Scanner scanner= new Scanner(System.in);
input = scanner.next();
This method finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

import java.util.Scanner;
class ScannerDemo{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your age");
int age=sc.nextInt();
System.out.println("age:"+age);
}
}

Related

Java if (Yes or No Statement)

Hey there I got into some trouble with my java Code.
I try to code a bit around with java for a few hours and I dont know much thats why im asking. I learn best by trying but I get into so many problems.
So: I want the scanner to scan the next Statement and if its "ja" it should do the if thing etc.
The problem is, when i try to compile it it has an error with the = s.nextInt thing. In the console it says: "cannot find symbole". I tried so many things I dont know what to do. Allready tried so much.
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = s.NextInt();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
thanks in advance.
EDIT: Problem solved. Thank you for every awnser. I try my best to Tag my posts better and to format my code better
Here:
String a = s.NextInt();
You want a to be String (which makes sense, as you want to compare it against other Strings later on); so you better use:
String a = s.nextLine();
instead!
The other method a) does not exist and b) nextInt() ... returns a number, not a string
I can see two errors, firstly you are taking a string input from the command line user so your scanner must be "scanner.nextLine()" which takes a string, as it stands you are expecting an integer value.
Second your "s.scanner" is not calling anything, you have declared your scanner with the name "scan", so you need to change that to "scan".
import java.util.Scanner;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("A flag has more than one colour?");
String input = scan.nextLine();
if (input.equals("yes")) {
System.out.println("well done");
} else {
System.out.println("wrong answer");
}
}
Try:
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = scan.nextLine();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
You have got a compilation error that should be
String a = scan.next();
Since scan is your scanner object where you are using String a = s.NextInt(); which is not at all an object of scanner.
Two issues, one is a is a String not an int and the second is Scanner.nextLine() (or nextInt() or next()). And, the local reference is scan (not s). Like,
String a = scan.nextLine();
You can use like this.
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
refrence: http://www.javatpoint.com/Scanner-class

Why do I keep getting the nosuchelementexception error?

I'm new to programming. I'm trying to get multiple inputs from the user by using Scanner class. I'm using net beans and trying to run and compile my code within the net beans IDE. The program runs and compiles whenever I do not close the scanner after asking for input. But when I attempt to close the scanner after every time I asked for input I get an the nosuchelementexception scanner closed error. In class, we were taught to close scanner after every time we ask for input from the user. My professor does this, also while using NetBeans and his program compiles and runs every time. Like me, he also only declares scanner once and uses the same variable multiple times while asking for input from the user.
import java.util.Scanner; // This allows us to use Scanner
public class GettingInput {
public static void main(String[] args) {
// ALWAYS give the user instructions. System.out.println("Enter an integer: ");
// Create a new scanner
Scanner keysIn = new Scanner(System.in);
// Specify the type of data/variable you are scanning in
int num = keysIn.nextInt();
// Close your scanner when you are done.
keysIn.close();
// ALWAYS confirm that you scanned in what you thought you did.
System.out.println("Your int: " + num);
// Repeat the process for a different data type
System.out.println("---------");
System.out.println("Enter a floating-point value:");
keysIn = new Scanner(System.in);
double num2 = keysIn.nextDouble(); // note the different method
keysIn.close();
System.out.println("Your floating-point: " + num2);
// Repeat it yet again
System.out.println("---------");
System.out.println("Now enter a string.");
keysIn = new Scanner(System.in);
String str = keysIn.nextLine(); // again, a different method
keysIn.close();
System.out.println(str);
}
}
This is code he had written, compiled and ran in class. When I try to run the same code it does not work.
I'm also using a Mac Book Pro and the latest version of Mac OS.
it happens because you closed the scanner and initiating the scanner object again. so it is better that you don't close the scanner where you know you are going to use it later again in your code, but you should do it once you are done with it.
Another thing is that, for different type of inputs you even don't need to create an entire scanner object again, you can just call appropriate methods of that scanner for your corresponding inputs type. Such that
import java.util.Scanner;
public class GettingInput {
public static void main(String[] args) {
Scanner keysIn = new Scanner(System.in);
int num = keysIn.nextInt();
System.out.println("Your int: " + num);
System.out.println("---------");
System.out.println("Enter a floating-point value:");
double num2 = keysIn.nextDouble();
System.out.println("Your floating-point: " + num2);
System.out.println("---------");
System.out.println("Now enter a string.");
String str = keysIn.next();
keysIn.close();
System.out.println(str);
}
}

Usage of hasNextInt() in java

I am a beginner and I am confused with using hasNextInt(). If it checks the input, then shouldn't we be using it after asking the user for input? However, in the given code below, it is used with if statement. Please advise.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your number");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
System.out.println("You entered an integer");
} else {
System.out.println("you didn't enter an integer");
}
}
}
The java.util.Scanner.hasNextInt() method returns true if the next
token in this scanner's input can be interpreted as an int value in
the default radix using the nextInt() method. The scanner does not
advance past any input.
So Scanner would be invoked upon user presses "Enter" and then it would evaluate if the next input provided by user is int or not.
You use it to test the user's input, so you are sure that when you call nextInt you won't have an exception because the input wasn't an int, it's also not moving he cursor forward:
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
}

Java reading from Standard in using Scanner giving wrong results [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am using netbeans.
I am trying to read standard in or arguments using Scanner. However whenever I try to display something, I get something completely different.
Scanner input = new Scanner(System.in);
System.out.println(input);
So, for example if the preset command line argument is "Awesome!"
I want it to print out Awesome! But I get some long gibberish such as :
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. you can use following methods of Scanner class (for your case its string) :
nextInt to input an integer
nextFloat to input a float
nextLine to input a string
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String user_value = in.nextLine();
System.out.println(user_value);
}
Here is the code you should use:
import java.util.Scanner;
public class InputTesting {
public static void main( String[] args ) {
Scanner input = new Scanner ( System.in );
String str1;
System.out.println("Input string: ");
str1 = input.next();
System.out.println( str1 );
}
}

Scanner not working? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to Java and I am trying to make a Java app where it asks you to spell "Java" and if you spelled it correctly it will type "yes", however, it is typing "no", what am I doing wrong:
package quiz;
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner kirill = new Scanner(System.in);
System.out.println(kirill.next());
String kirill2 = "Java";
if (kirill.equals(kirill2)){
System.out.println("yes");
}else{
System.out.println("no");
}
System.out.println(kirill);
kirill.close();
}
}
Running code:
Java
Java
no
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=4][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
if (kirill.equals(kirill2)){
kirill is the Scanner object, not the string. Try something like this:
Scanner kirill = new Scanner(System.in);
String userInput = kirill.next();
if (userInput.equals("Java")){
...
Also, note that your code will print "yes" if the user types "Java is a programming langauge." If you only want it to validate with just "Java," replace next with nextLine.
package quiz;
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
String kirill;
String kirill2 = "Java";
Scanner input = new Scanner(System.in);
kirill = input.next();
if (kirill.equals(kirill2)){
System.out.println("yes");
}else{
System.out.println("no");
}
System.out.println(kirill);
input.close();
}
}
Minor issue with your Scanner. You were trying to match a Scanner to a String. You can't to that silly!
Save what you're reading into a String instead of comparing the Scanner object with a String. Your main method should look something like
public static void main(String[] args) {
Scanner kirill = new Scanner(System.in);
String input = kirill.nextLine();
System.out.println(input);
String kirill2 = "Java";
if (input.equals(kirill2)){
System.out.println("yes");
}else{
System.out.println("no");
}
System.out.println(kirill);
kirill.close();
}
Also, note that .next() will only scan to the first delimiter (which is by default any whitespace), so if you want to make sure that the user only types "Java", then you should probably use .nextLine() instead of .next().
Let's take a quick look on your code, inside main():
Scanner kirill = new Scanner(System.in);
creates a scanner and assigns it to a variable, OK.
System.out.println(kirill.next());
Prints what the user types, but doesn't assign it to anything.
String kirill2 = "Java";
Just a String variable... OK.
if (input.equals(kirill2)){
If the scanner equals some text, then proceed. Hold on, you see what I just said? Comparing a Scanner and a String. This wouldn't end up right. Imagine a robot, and you give it a cup of water and a paper with "water" written on it, and ask if they are equal. Obviously they're not, and they can't be. You are comparing a set value with another set value, instead of the user's input. The following would be correct:
package quiz;
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //creates a scanner
String text = "Java"; //creates the text to be compared
String input = scan.nextLine(); //read some arbitrary text the user types
if (input.equals(text)){ //checks if user's input is equal to text
System.out.println("yes");
}else{
System.out.println("no");
}
scan.close(); //closes the Scanner
}
}
Although not required, it's a good practice to name variables after what they do or represent, or you will get confused very quickly...
So here, an easier method would be:
package quiz;
import java.util.Scanner;
public static void main(String[] args) {
String userInput;
String word = "Java":
Scanner in1 = new Scanner(System.in);
userInput = in1.next();
System.out.println( userInput );
if (word.equals(userInput)) {
System.out.println("Yes!");
}else{
System.out.println("No.");
}
System.out.println( userInput );
userInput.close();
}

Categories