How do I check what the user wrote in Java? [duplicate] - java

This question already has answers here:
How can I read input from the console using the Scanner class in Java?
(17 answers)
Closed 7 years ago.
I'm trying to make it so when the user writes Start the program does something, but I'm unsure of how to what the user actually wrote.
This was my first attempt at it:
import java.util.Scanner;
public class Suhwag {
public static void main (String args[]){
Scanner scanNer = new Scanner (System.in);
System.out.println("Please write \"Start\" to begin.");
String stinky = "Start";
if (stinky == scanNer);
But with this, I got the error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Incompatible operand types String and Scanner
After I saw the error, I tried to convert scanNer to a string as seen here:
import java.util.Scanner;
public class Suhwag {
public static void main (String args[]){
Scanner scanNer = new Scanner (System.in);
System.out.println("Please write \"Start\" to begin.");
String stinky = "Start";
String input = scanNer.nextLine();
if (stinky == scanNer);
But the same error message still appears. Anyone know what I could do to make it work?

You're trying to compare a Scanner object with a String object. First, you could input the string with the following line:
String myString = scanNer.next()
Then, compare it with "Start":
if ( myString.equals( "Start" ) )
{
...
}

You are comparing a String to a Scanner object.
You should use the equals method to compare String's
No need for the semi-colon after the if (see below)
In reference to your last code snippet:
if (stinky.equals(input)){
//do something
}

in the latter code area you said in your if statement:
stinky == scaNer
it should be
stinky.equals(input)

in your if statement, you compared still your scanner with ur stinky
change your if statment to this
if (input.equals(stinky)){<code here>}
your previous code didnt work because you compare a scanner with a string

Related

Can't get program to break on specific string [duplicate]

This question already has answers here:
Scanner only reads first word instead of line
(5 answers)
Closed 2 years ago.
The code works for the most part, but if I type "No way" it still stops the loop. Should I set it up a different way or use a length function ? Everything I've searched on breaking a loop used integers.
See the code below:
import java.util.Scanner;
public class CarryOn {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.next());
if (answer.equalsIgnoreCase("no")){
break;
}
}
}
}
Using .next in this case only stores "no" in "no way". Use .nextLine instead:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.nextLine());
if (answer.equalsIgnoreCase("no")){
break;
}
}
Output:
Shall we carry on?
no way
Shall we carry on?
no
Check this post for more information.
scanner.next()
only reads a single token. No way is two tokens: No and way.
Use scanner.nextLine() instead, if you want to read the whole line.

Can use Scanner only once [duplicate]

This question already has answers here:
Close a Scanner linked to System.in
(5 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm kinda new to java and used to write in Python. So when it comes to getting User Input I'm allways annoyed by how many lines of Code I need to perform such task. So I tried to make my own class that simplifies that process. I wanted to perform something like this:
input("This is written in the console: ")
Inside the Console:
This is written in the console: |
Here is the code so far:
public static String input(String text) {
Scanner scanner = new Scanner(System.in);
System.out.print(text);
String x = scanner.nextLine();
scanner.close();
return x;
}
When I use the class once, everything works just fine, but when I try to use it again, I get an Exception:
public static void main(String[] args) {
input("Input: ");
input("Input 2: ");
}
Output:
Input: blaaa
Input 2: Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at NumberConverter.input(NumberConverter.java:124)
at NumberConverter.main(NumberConverter.java:7)
I really don't know why that keeps happening. Please help me, thanks.
Thanks to "SomeJavaGuy" I finally got it to work:
public class NumberConverter {
private static Scanner scanner = new Scanner(System.in);
public static String input(String text) {
System.out.print(text);
String x = scanner.nextLine();
return x;
}
public static void main(String[] args) {
input("Write your Input: ");
input("Write another Input: ");
scanner.close();
}

Java - program skips Scanner(System.in) [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 5 years ago.
public static char[] puzzleInput() {
printEnterPuzzleMessage();
Scanner puzzleS = new Scanner(System.in);
if(puzzleS.hasNext()) {
char[] puzzle = puzzleS.next().toCharArray();
while(!isLegalPuzzleStructure(puzzle)) {
printIllegalPuzzleMessage();
puzzleInput();
}
return puzzle;
}
puzzleS.close();
return null;
}
public static void main(String[] args) throws Exception{ //Q - 8
Scanner fileName = new Scanner(System.in);
if(!fileName.hasNext()) {
System.out.println("No argument has been received");
System.exit(0);
}
String filePath = fileName.nextLine();
fileName.close();
Scanner vocabulary = new Scanner(new File(filePath));
String[] vocabularyArr = scanVocabulary(vocabulary);
vocabulary.close();
printReadVocabulary(filePath, vocabularyArr.length);
printSettingsMessage();
printEnterPuzzleMessage();
char[] puzzle = puzzleInput();
Hi, a beginner in Java is here.
In the function puzzleInput, I open a Scanner to get an input from the user. For some reason, the program won't give me a chance to put in input, and therefor the argument (puzzle) gets a null as default, and later when puzzle is needed not as a null - throws a NullPointerException.
There are many other functions in the code, but most of them are just a print commands, and the ones who are not were being checked by me, and are OK.
The problem is just the scanner won't give me a chance to put in an input.
Some points I'd like to clarify further:
1. The first Scanner (fileName) is not being skipped by the program, and I'm able to give it an argument.
2. I made sure I closed all the other scanners i've opened before.
Can someone explain me what I'm doing wrong?
program won't give me a chance to put in input
Your problem is that you are closing your Scanner in main:
Scanner fileName = new Scanner(System.in);
...
fileName.close();
This in turn closes the System.in input-stream which then cannot be reused in your puzzleInput() method because it is already closed. The right thing to do here is to pass in the Scanner variable into your puzzleInput() method and continue to reuse it there and not try to open up a new Scanner.
public static char[] puzzleInput(Scanner scanner) {
printEnterPuzzleMessage();
if(scanner.hasNext()) {
...
// don't close it here
return null;
}
...
Scanner scanner = new Scanner(System.in);
...
puzzleInput(scanner);
Couple of other comments:
Calling a Scanner fileName is not a good pattern. Choosing good names for your variables will help make the code self-documenting. scanner would be a better name of course.
When dealing with any input/output, it is a good practice to wrap any opening method in a try/finally block so it gets close properly. See also the try-with-resources functionality added in Java 7.
If you want a chance to do something with the input with a prompt, why not assign it to a String variable? This allows you to manipulate the input however you want later on too.
String input = scannerName.nextLine();

Unexpected behavior of Scanner [duplicate]

This question already has answers here:
Close a Scanner linked to System.in
(5 answers)
Closed 5 years ago.
In below code have two methods scanner1 and scanner2 in both methods new object of Scanner is created and scanning the input after that closing the Scanner by invoking close().
import java.util.Scanner;
public class TestScanner {
public static void scanner1(){
Scanner sc = new Scanner(System.in);//created object of scanner
System.out.println("Enter string :");
String input = sc.nextLine(); //scanning input
sc.close(); //closing scanner object
}
public static void scanner2(){//problem in scanner2
Scanner sc = new Scanner(System.in);//created another scanner object
System.out.println("Enter String :");
String input = sc.nextLine();//scanning object
sc.close();//closing the input
}
public static void main(String[] args) {
scanner1();
scanner2();//problem here
}
}
For scanner1 method working fine but when scanner2 method get invoked getting the below error:
Enter string : India Exception in thread "main"
java.util.NoSuchElementException: No line found Enter String : at
java.util.Scanner.nextLine(Unknown Source) at
cheggapril.TestScanner.scanner2(TestScanner.java:17) at
cheggapril.TestScanner.main(TestScanner.java:24)
Problem is why in scanner2 method scanner not able to scan the user input even in this method creating fresh one object of Scanner.
Please give some clear explanation. any ref or example will be much greatful.
The reason is quite simple, closing the 1st scanner object closes internally too the input stream which is actually being used by the second scanner
your options are: use only one scanner or close those when you are sure all of them are not required anymore..

Scanner objects in methods and NoSuchElementException [duplicate]

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 7 years ago.
I have really tried to find the answer through the threads but still hope to get some feed back.
The code below is bad style I think but I don't know why it shoot me a
java.util.NoSuchElementException after enter the number since I make two Scanner objects for two methods and I should be able to start a new input. And if I erase the input.close() in inputAndPrintNumber(), it works and compile correctly. I really hope to know why and how to fix it if I still use two Scanner obj and without erasing the input.close() if possible.
import java.util.*;
public class t{
public static void main(String [] args){
inputAndPrintNumber();
inputAndPrintString();
}
public static void inputAndPrintNumber(){
Scanner input = new Scanner(System.in);
String s = input.nextLine();
System.out.print(s);
input.close();
}
public static void inputAndPrintString(){
Scanner input2 = new Scanner(System.in);
int a = input2.nextInt();
System.out.print(a);
}
}
I don't even sure whether the code below is better or any better idea?
import java.util.*;
public class t{
public static Scanner input = new Scanner(System.in);
public static void main(String [] args){
inputAndPrintNumber();
inputAndPrintString();
input.close();
}
public static void inputAndPrintNumber(){
String s = input.nextLine();
System.out.print(s);
}
public static void inputAndPrintString(){
int a = input.nextInt();
System.out.print(a);
}
}
When you call scanner.close() it not only closes scanner, but also stream from which it reads data, in this case System.in. So if you are going use System.in later don't close it (if it is closed, we can't reopen it and read any data from it, hence exception).
Your second code example solves this problem because Scanner is being closed when you are sure that nothing else will be read from input stream.
BTW it seems that you mixed places where nextLine and nextInt should be invoked (nextLine seems to be more appropriate for inputAndPrintString while nextInt for inputAndPrintNumber).

Categories