I am trying to emulate this,
$ are you sure (y,n)? y
Where if the user hits enter, the default option would be read from nextLine() using the Scanner (default being the value already populated in the System.in which is in the above example the String y).
if the user wants to change the value he should hit (backspace/delete) and enter a new value.
is this scenario possible using the Scanner and System.in?
This question is not the same, I want to be able to write to System.in so when I do nextLine() to the Scanner object it will return the default value I have wrote. it is something I always see in bash scripts. In that question he is just outputting the default value within the printed string and then defaulting to it if the user hits enter on an empty input.
This is the closest question I have found, and the answer is saying it is impossible to do.
What do you think?
EDIT1:
Read Tom's comment below.
There is no benefit in pursuing such effect.
Related
*EDIT - SOLVED: After instantiating the Scanner Object, I used a delimiter as follows:
scanner.useDelimiter("");
Prior to this, I did try a delimiter that looked something like this (the exact code is available on Stack Overflow):
scanner.useDelimiter("\\p{javaWhitespace}");
...but it didn't work very well.
Thank you, everyone. If you're having this very same issue, try the first delimiter. If it doesn't work, upgrade your JDK to 13 then try it again.
Ok, my goal is to have a user input a credit card number which I would then like to store in an ArrayList of Integers and subsequently pass this list to my functions which will perform the Luhn algorithm in order to validate the provided number. Once the user presses Enter, the processing begins. This is a console application, nothing fancy.
Everything works beautifully...except the user-input part. None of the user-input is being stored into the declared ArrayList. I've inserted a print message to give me the size of the list just after the pertinent while-loop and....yep, 0. I also pass this list into a custom lengthChecker(ArrayList<Integer> list){} function subsequent to the relevant while-loop and it's printing my custom error-message.
I have declared local int variables within the scope of the while-loop and that wasn't helping much. I have tried getting the user's input as Strings and storing them in an ArrayList<String> list; then parsing the input but that didn't work very well (especially as I need the Enter key to behave as a delimiter such that the next steps can take place)
Anyways, here is the code to the function in question. Am I missing something obvious or should I just quit programming?
public void userInput() {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
System.out.println("Please input the card-number to be checked then press Enter: ");
while(scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
System.out.println("Length of list: " + list.size());
listLengthChecker(list);
scanner.close();
}
Thank you in advance.
I don't have the full context on all the code you've written to be able to solve your problem, but I can guess at what's going on. If you want to run any user I/O (such as the scanner), it must occur within the main method. I can only assume that you run your userInput() function within the main method in your class. However, because your userInput() function doesn't have the static keyword in its definition, it can't be accessed without initialising an object of the class - but as far as I can tell from your code, there is no object that the method could refer to. Add the static keyword (i.e. initialise the method as public static void userInput()) to be able to run the function as you intend.
As for the while loop - there's a small chance that this is a difference in Java versions (I use Java 11), but while(scanner.hasNextInt()) won't stop being true at the end of your line or when you press enter - only when you insert something (such as a character) that cannot be interpreted as an integer.
This while loop untill you enter any non integer value.
You finished entering all the integer values and then your program will print your list elements.
How would you reprint a line after taking an input from the user (from terminal)?
I realise that you could reprint a line using:
System.out.print("\r foo");
System.out.print("\r bar");
Which will produce the output:
bar
but once you take an input from the user, this doesn't seem to work. For instance:
System.out.print("\r foo");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.print("\r bar");
If you type in 1 as the input, you get:
foo1
bar
Can you reprint on the same line as foo (or more specifically, foo1) once the user has provided an input?
The key here is likely to be "raw" vs "cooked" mode of input. To do what you want, you will need to use "raw" mode where you collect each character as it is typed, and decide what to do with it, including whether you echo it to the console or not.
Cooked mode is more common for simple command line program input, and basically means "Give me the user's input, one line at a time". And "one line at a time" generally translates to "when the user presses enter." Most "cooked" implementations echo the keyboard input to the console.
For a host of reasons, doing "raw" mode in CLI programs is difficult -- not impossible, but difficult. I will spare the details in this venue (which are numerous and do not lend themselves to easy copy and paste here), and instead point you to the resource I used when attempting the same a few years ago:
Non blocking console input in Python and Java
A quick hunteke summary: the terminal/console needs to change state, not just your program, and there is no portable method for doing so. You'll be outsourcing to other libraries or programs to do what you want -- just don't forget to undo it when your program quits, or your users won't be happy!
Was instructed, for a university-level assignment, to receive user input through "standard input". Google was a bit scarce as to what precisely this means.
While I could (and for the sake of my grade, will) go to my professor for clarification, I figured I would ask Stack Overflow so if anyone in the future has the same question they can find this and do without the research I performed; additionally, I appreciate the history lesson some Stack Overflow contributors provide.
Basically, what I found was receiving user input was originally done via standard input methods (hardware). However, and this is where things get complicated, now the process has been abstracted. Instead of requiring hardware, now, through something called redirection/pipelining, we can modify where the input will come from.
In addition to clarifying what the above means, I, personally, am interested in a Java-specific response.
Simply put, there are three "common" ways of receiving user input in Java
SO Source: BufferedReader vs Console vs Scanner
Basically, what I got from the above, is that the differences involve optimization for what you intend to do with the input and how the input is stored/treated, in terms of whether it is received as the ASCII Integer or whatever.
My question is are all three of the above methods considered standard input? Is there a way of obtaining user input NOT through standard input? By user input I mean something the user inputs manually upon program execution, not transferring data from a file or anything like that.
Furthermore, when receiving input in the above way, is it worth checking for null?
Example:
Scanner a = new Scanner(System.in);
String testInput = a.nextLine();
if (testInput == null)
How can something input by the user ever point to nothing in memory (i.e. null?) is this ever possible?
I've been searching overflow questions and googling it for about half an hour and can't find an answer for this.
At first I thought it might be that I'm not closing my Scanner object. I added
inp.close();
after all my code,but still nothing.
I'm using Eclipse to create a simple Binary Search algorithm.
My problem is that it is not keeping my input. And what's even weirder is that it only accepts "5".
After pressing enter it only creates more spaces. It doesn't move on to the rest of the program.
I've also tried entering more values under the "skipped" ones without any success.
Here's some screenshots
nextInt() reads scans the next token of the input as an int.
If the input is not an int, then an InputMismatchException is thrown.
You can use next() to read the input, whatever its type is. And you can hasNextInt() to make sure the next input is an int:
Scanner inp = new Scanner(System.in);
if(inp.hasNext()) {
if(inp.hasNextInt()) {
int n = inp.nextInt();
// do something with n
} else {
String s = inp.next();
// do something with s
}
}
Actually, I have a theory - your Scanner code is working just fine, it's your binary search code that's broken. Whatever it's doing works on an input of 5 but falls into an infinite loop for other inputs.
Consider breaking up your input parsing code from your binary searching code (e.g. do input parsing in main() and define a binarySearch() function that main() calls) so that you can test them separately.
I'm writing a Mastermind program where it takes input for the guess, but I need to make sure that it only takes 4 characters of input. So if someone entered anything other than 4 characters, it would prompt for reentry. I know this isn't hard at all, I'm just drawing a blank and haven't been able to find an answer on here anywhere.
Lets try to do it, one step at a time.
Get user input in your program. If it's standard input, one way to pull it is with System.in, which is an InputStream.
Store the input in an intermediate variable. The type of this variable can be String.
If needed, cast the value to a type which is the most relevant to your application's requirement. Before that check input for bad values like null.
Perform the logic on the input, which in your case is finding out whether the length of the input is 4.
Prompt again for input if the current one doesn't meet the requirement. One way to do it is to put your relevant code in a loop which terminates only when you get the right input.
And if that doesn't work, you're most welcome to ask again including code that shows your effort.