So, in Java, I want the user to provide either Y or N to my prompt. Lets say (dream sequence begins with swirly sounds) I am currently using this code:
String output = "";
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("[P]ast or [F]uture?");
String input = scan.nextLine().toLowerCase();
if (input.equals("p") || input.equals("f")){
output = input;
break;
} else {
System.out.println("Please provide a valid answer.");
}
}
There has got to be a more efficient way of doing this. Can anyone enlighten me?
There is no way you can force the user to type in something. You'll have to sanitize the data and throw an error at the user when he types in something wrong, much like your code is doing now.
Use a GUI library such as Swing or JavaFX and only allow the allowable input. For instance if this were Swing and the user were entering input into a JTextField, you could add a DocumentFilter to the JTextField's document, preventing the user from entering anything but 'y' or 'n'.
Have you tried hasNext(String pattern) to validate that the next token consists of your desired pattern?
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
http://www.tutorialspoint.com/java/util/scanner_hasnext_pattern.htm
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Error");
sc.next();
}
Related
I am trying to implement a simulator that has certain commands the user can input.
One of these commands is "s" which when entered should step through one instruction of the assembly file. However there is another instruction with the format "s num" where the user can define just how many instructions they want to step through.
I check for this
if(input.equals("s"))
{
//check for num next
if(user.hasNextInt())
{
input = user.next();
step(Integer.parseInt(input), assembler);
}
else
{
step(1, assembler);
}
}
However the problem is if the user only enters "s" the scanner will wait for the next input rather than just calling step. My idea is if there is an int after the s was input then proceed with the num step, other wise just call step.
Any help is greatly appreciated!
I would split the input into two parts and then treat it. For example,
String input = user.nextLine();
String array[] = input.split(" ");
if(array.length<2){
//check for `s`
}else{
//check for `s num`
}
you could try this:
if(input.equals("s"))
{
step(1, assembler);
}
else if(input.startsWith("s") && input.length() > 2)
{
step(Integer.parseInt(input.substring(input.indexOf(" ")+1)), assembler);
}
If control were to go inside the else if block, the current solution assumes that there is always a number after the String s with a white space delimiter in between them, but you can go on further and do more validations if necessary.
I am trying to check if a user entered a number and if not, then it uses a default number like 10. How do i check if the user just presses enter and doesn't enter anything in Java
input = scanner.nextInt();
pseudo code:
if(input == user just presses enter without entering anything){
input = 10;
}
else just proceed with input = what user entered
//scanner is a Scanner
int i; // declare it before the block
try {
i = scanner.nextInt();
}
catch (InputMismatchException ime) {
i = 10;
}
// i is some integer from the user, or 10
First things first, geeeeeez guys, when the OP says something like
"I don't want an exception, i want i = 10 if nothing is entered, so what do i do"
That should clue you in that he probably doesn't know too much about exceptions (maybe even java) and might need a simple answer. And if that's not possible, explain to him the difficult ones.
Alright, here's the plain and simple way to do it
String check;
int input = 10;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
else
{
input = Integer.parseInt(check);
}
Let me explain what this code is doing. You were originally using nextInt() to get your number for input, correct? The problem is, nextInt() only responds if the user actually inputs something, not if they press enter. In order to check for enter, we used a method that actually responds when the user presses enter and used that to ensure that our code does what we wanted to. One thing I recommend using is an API, Java has one.
Here's the link for the API HERE
And here's the link for the actual method I used HERE. You can find descriptions and instructions on many methods you'll run into on this API.
Now, back to my answer, that's the easy way to do it. Problem is, this code isn't necessarily safe. It'll throw exceptions if something goes wrong, or if someone is trying to hack into your system. For example, if you were to enter a letter instead of pressing enter or entering a number, it would throw an exception. What you've been seeing in the other answers is what we call exception handling, that's how we make sure exceptions don't happen. If you want an answer that'll catch most of these exceptions, you need to make sure your code catches them, or avoids them all together (I'm simplifying things immensely). The above answer is working code, but isn't safe code, you wouldn't ever use something like this all by itself in real life.
Here is something that might be considered safe code. And no exceptions to keep it simple! ;)
import java.util.Scanner;
public class SOQ15
{
public Scanner scanner;
public SOQ15()
{
scanner = new Scanner(System.in);
int input = 10;
boolean isAnInt = true;
String check;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
for(int i = 0; i < check.length(); i++)
{
if(check.charAt(i) >= '0' && check.charAt(i) <= '9' && check.length() < 9)
{
//This is if a number was entered and the user didn't just press enter
}
else
{
isAnInt = false;
}
}
if(isAnInt)
{
input = Integer.parseInt(check);
System.out.println("Here's the number - " + input);
}
}
public static void main(String[] args)
{
SOQ15 soq = new SOQ15();
}
}
I don't have time to go into all the details right now, but ask and I'll gladly respond when I get the time! :)
Well if you are using scanner, given the details provided, you can try:
Scanner in = new Scanner(System.in);
if in.hasNextInt(){ //Without this, the next line would throw an input mismatch exception if given a non-integer
int i = in.nextInt(); //Takes in the next integer
}
You said you wanted a default of 10 otherwise so:
else {
int i = 10;
}
In my console application, I give the user the option to type "exit" at any point to return to the main menu. As the user enters data, i prompt him/her through the console for various things, and collect the data using scanner.
My question is how can I check to see if the user entered "exit" after each prompt (as opposed to the requested information) without having to use the same if statement after each step?
As I see it, any kind of while or for loops are insufficient because they only check the condition at the beginning, when I need to check the condition between inputs, and I need each input/prompt to execute only once per iteration.
The key here is that each prompt/code executed between the checks is DIFFERENT, so loops won't work.
Here is some example code:
String first;
String second;
Scanner input = new Scanner(System.in);
//prompt user for input
first = input.nextline();
if(first.equals("exit")){
//return to start menu
input.close();
return;
}
//prompt user for DIFFERENT input
second = input.nextline()
if(second.equals("exit")){
//return to start menu
input.close();
return;
}
If I understand you correctly, I recommend a do-while loop. It will first take text the first time, perform an action, and if it is exit it will break the loop, otherwise it will repeat.
do{
text = input.nextLine();
//whatever code you want here to perform with input
}while(!(text.equals("exit"));
Write a method...
public boolean isExit(String value) {
return value.equals("exit");
}
You can then check this method each time...
String value = input.nextLine();
if (!isExit(value) {
// Handle the normal text
} else {
// Handle the exit operations...
}
You could put additional code in the check, but I would prefer to have an additional method that handles the exit operation...for example...
String value = input.nextLine();
if (!isExit(value) {
// Handle the normal text
} else {
doExit();
}
Take a look at Defining Methods for more details...
Updated
Focus on the idea that a method should do a single job and have no side effects...
Having said that, I would setup my code in such away that if the user enters exit at the prompt, the method can exit of it's own accord, without the need for return; statement...
For example...
public int selectYourMeal() {
// Prompt...
int option = -1;
String value = input.nextLine();
if (!isExit(value) {
// Handle the normal text
} else {
option = EXIT_OPTION;
}
return option;
}
Where EXIT_OPTION is a special value, which the caller and identify and deal with as it sees fit.
I'm also old school, in that I was taught that a method should have one entry and one exit point, you really want to avoid having multiple exit points within your methods, as it becomes very difficult to follow the logic...
I would suggest you use an List<String> of words. You can return it. Also, it's a really bad idea to close a Scanner wrapping System.in, once you do you cannot re-open it.
List<String> words = new ArrayList<>();
Scanner input = new Scanner(System.in);
for (int i = 0; input.hasNextLine(); i++) {
String line = input.nextLine();
words.add(line);
if (line.equalsIgnoreCase("exit")) {
break;
}
}
System.out.println(words);
return words;
I have a program that needs to read lines of input. It needs to be many lines at once. For example:
As I enter my time machine or
maybe not,
I wonder whether free will exists?
I wonder whether free will exists
maybe not
as I enter my time machine or.
That all gets entered at one time by the user. I was trying to use .hasNextLine() method from Scanner class, but it is not returning false.... it waits for input again. Ive been looking around for a solution and it appears that .hasNextLine() waits for input, but i do not know what alternative to use. Any suggestions? The actual code looks like:
while(input.hasNextLine());
{
line += input.nextLine();
}
Thanks for your help
Perhaps you should use some sort of "stop" sequence meaning when the user enters a particular character sequence, it will break out the loop. It might look something like:
public static void main(String args[]){
final String stopSequence = "/stop";
final Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
while(!input.equalsIgnoreCase(stopSequence)){
//process input
input = reader.nextLine();
}
}
I am trying to write some validation code in my class for my GUI. How would I go about getting the text from a JTextField into a while statement and prompting a JOptionPane for the user to enter the necessary number(double)? To be more specific, how do I check if what I got from the JTextField is a string/string+number/anything other than a number?
String text=JTextField.getText();
while(text.equals*a string or anything but a number*);
JOP("Invalid input ............ etc...
If you have time, here is my GUI and my class. I am trying to do this for the rest of the methods. But the answer to the above will suffice.
http://www.mediafire.com/?f079i1xtihypg1b
http://www.mediafire.com/file/f079i1xtihypg1b/FinanceGUI.java
Update:
This is what I have so far:
//get the text entered in the amountRentText
//JTextField and parse it to a Double
String amtRentIn=amountRentText.getText();
try{Double.parseDouble(amtRentIn);}
catch(NumberFormatException nfe){
while()
amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
"enter your rent: ");
}
double rent= Double.parseDouble(amtRentIn);
fin.setRent(rent);
What do I put in the while?
String amtRentIn=amountRentText.getText();
boolean incorrect = true;
while(incorrect){
try{Double.parseDouble(amtRentIn);incorrect = false;}
catch(NumberFormatException nfe){
amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
"enter your rent: ");
}
}
javax.swing.InputVerifier is designed for this. Your implementation of verify() could invoke parseDuble(). Here's another example.
A "cheap" not too beautiful solution that occurs to me would be using the Double.parseDouble(..) on that string, and being ready to catch the parsing exception that would occur in the event the String had any non-numeric content.