Java: Checking for changes in a String with BufferedReader - java

If trying to get user input into a string, using the code:
String X = input("\nDon't just press Enter: ");
and if they did't enter anything, to ask them until they do.
I've tried to check if it's null with while(x==null) but it doesn't work. Any ideas on what I am doing wrong/need to do differently?
input() is:
static String input (String prompt)
{
String iput = null;
System.out.print(prompt);
try
{
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
iput = is.readLine();
}
catch (IOException e)
{
System.out.println("IO Exception: " + e);
}
return iput;
//return iput.toLowerCase(); //Enable for lowercase
}

In order to ask a user for an input in Java, I would recommend using the Scanner (java.util.Scanner).
Scanner input = new Scanner(System.in);
You can then use
String userInput = input.nextLine();
to retrieve the user's input. Finally, for comparing strings you should use the string.equals() method:
public String getUserInput(){
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
if (!userInput.equals("")){
//call next method
} else {
getUserInput();
}
}
What this "getUserInput" method does is to take the user's input and check that it's not blank. If it isn't blank (the first pat of the "if"), then it will continue on to the next method. However, if it is blank (""), then it will simply call the "getUserInput()" method all over again.
There are many ways to do this, but this is probably just one of the simplest ones.

Related

Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration

https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();

If user presses enter (without anything else) how can I print out the line ("please give a valid command")?

I have a program in java where the user have to give command. However if he presses enter without anything else the program stops and he gets this:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at UserInterface.main(UserInterface.java:43)
How is it possible that I can detect with the program that no line is found, and I print out the following ("please give a valid command").
I have tried this:
Scanner keyboard = new Scanner(System.in);
String command = keyboard.nextLine();
if (command == "") {
System.out.println("please give a valid command");
}
1) You can use the method isEmpty() from the Scanner itself to find out if an input is "nothing".
Try this:
Scanner keyboard = new Scanner(System.in);
String command = keyboard.nextLine();
if (command.isEmpty())
{
System.out.println("Please give a valid command.");
}
2) You can't compare two Strings like you did either. If you want to compare them you need to use the equals(Object anObject) method.
Here is an example:
Scanner keyboard = new Scanner(System.in);
String command = keyboard.nextLine();
if (command.equals("A String"))
{
System.out.print("Success");
}
Surround the statement with try/catch
...
String command = "";
try {
keyboard.nextLine();
} catch (Exceptionn e) {}
...
This will catch the exception.
Try this:
if(command.equals("")){
System.out.println("please give a valid command");
}

Why I get the java.lang.NullPointerException? [duplicate]

This question already has answers here:
System.console() returns null
(13 answers)
Closed 7 years ago.
I want to input a name and to print the first char ....
public class Test {
public static void main(String[] args) {
Console console = System.console();
System.out.println("Type your name : ");
String inputChar = console.readLine();
char firstChar = inputChar.charAt(0);
System.out.println(firstChar);
}
}
Some IDEs will return NPE for Console class. you can use the Scanner class and do it easily:
try this:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a Name:");
String s = scan.next();
System.out.println(s.charAt(0));
this will print the first letter of your input String.
Using the Console class can a bit unreliable at times.
For reading console input, it would be preferrable to use either the Scanner class or a BufferedReader.
You can use a Scanner like :
Scanner scanner = new Scanner(System.in); // System.in is the console's inputstream
System.out.print("Enter text : ");
String input = scanner.nextLine();
// ^^ This reads the entire line. Use this if you expect spaces in your input
// Otherwise, you can use scanner.next() if you only want to read the next token
System.out.println(input);
You can also use BufferedReader like :
pre Java 7 syntax
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter text : ");
String input = br.readLine();
System.out.println(input);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
Java 7 syntax
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("Enter text : ");
String input = br.readLine();
System.out.println(input);
} catch (Exception e) {
e.printStackTrace();
}
Note: You need to use a try-catch statement when calling br.readLine() because it throws an IOException.
You can use Scanner if you want to read tokens (chunks of text separated by spaces). Use a BufferedReader if you want to simply read from the InputStream.

Scanner Ignores Some Inputs (System.in)

I've recently come along this frustrating problem, where the scanner completely ignores some inputs from the System.in inputstream. Here's an example:
Do you want a cookie? Yes or no.
Now, I type yes:
yes
Result:
Cookie for you!
Now, if I say no:
no
no
Result:
No Cookie for you.
Get it? If I say yes it just accepts it. If I say no, I have to type it 2 times.
If you really need some code. Here's some of that :)
public static void main(String[] paramArgs){
MainEW sMain = new MainEW();
Scanner s = sMain.scanner;
System.out.println("Enter a file path.");
System.out.println("Example: /Users/Some_User/Desktop/Some_Folder");
String defPath = s.next();
System.out.println("Enter a name for the file.");
String defName = s.next() + ".txt";
System.out.println("Now, enter what you want to write to the file.");
s.nextLine();
String defText = s.nextLine();
System.out.println("Do you want to create a new file? Yes or No");
if (s.next().equalsIgnoreCase("yes")) {
WriterEW writer = new WriterEW(defPath, defName, defText, true);
return;
} else if (s.next().equalsIgnoreCase("no")) {
WriterEW writer = new WriterEW(defPath, defName, defText, false);
return;
} else {
System.out.println("Invalid input.");
}
}
Thanks :)
When you type "no", the else if block calls next() again, asking for more input.
Instead of calling s.next() in each case, call it just once before you start your if conditions.
String response = s.next();
if(response.equalsIgnoreCase("yes")){
WriterEW writer = new WriterEW(defPath, defName, defText, true);
return;
}else if(response.equalsIgnoreCase("no")){

Using the standard/output stream as string input/output

I have an assignment stating that "You can assume that input will come from standard input in a stream. You may assume that the markers have access to all standard libraries".
How do I go about reading several lines/inputs and saving all the inputs as one string and then outputting that string from a function?
Currently this is my function, but it's not working properly, at one stage it wasn't reading more than one line and now it doesn't work at all.
public static String readFromStandardIO() {
String returnValue = "";
String newLine = System.getProperty("line.separator");
System.out.println("Reading Strings from console");
// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
System.out.println("Enter text...\n");
while (!(reader.readLine() == reader.readLine().trim())) {
userInput = reader.readLine();
returnValue += userInput;
}
System.out.println("You entered : " + returnValue);
return returnValue;
} catch (Exception e) {
}
return null;
}
Thank you for the assistance!
The problem is you're calling reader.readLine() three different times, so you'll end up comparing two completely different strings and then recording yet another one.
Also, it's generally frowned upon to compare strings using == (as comparing Objects with == asks if they are the same actual object (yes, Java's forgiving in that regard with strings, but it's still frowned upon)).
You'll need to do something more akin to:
public static String readFromStandardIO() {
String returnValue = "";
System.out.println("Reading Strings from console");
// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println("Enter text...\n");
while (true) {
userInput = reader.readLine();
System.out.println("Finally got in here");
System.out.println(userInput);
returnValue += userInput;
if (!userInput.equals(userInput.trim())) {
break;
}
}
System.out.println("You entered : " + returnValue);
} catch (Exception e) {
}
return returnValue;
}

Categories

Resources