Cannot make Scanner String method work - java

I'm trying to create a Scanner method for strings that returns the value entered by the user only if it is not blank (whitespace, user hitting 'enter' immediately etc..). If the user does this I want to print out an error message and have the loop return to the beginning again and await a new user input. If correct, I want the method to return the correct input value.
My code is as such:
private static final Scanner scr = new Scanner(System.in);
private static String readString(){
while(true){
String command = scr.next();
if(command != null && !command.trim().isEmpty()){
return command;
}
System.out.println("You have to type something");
}
}
Right now when I run this method in other methods if I leave a blank or simply hit 'enter' my output simply leaves a blank space until I type a string such as 'abc'. Then it returns that value.
Any helpful advice is appreciated!

Replace src.next() with src.nextLine()
private static final Scanner scr = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(readString());
}
private static String readString() {
while (true) {
String command = scr.nextLine();
if (command != null && !command.trim().isEmpty()) {
return command;
}
System.out.println("You have to type something");
}
}

Related

java method calling magic 8 ball

Here are the parameters:
Create a method called get8BallAnswers (2 point)
The method should have no parameters
The method will build the array of possible String answers (from BA5), and return the entire array
Overload the get8BallAnswers method (2 points)
The method should have 1 integer parameter, where the user can pass a random number to it
The method should return 1 possible String answer from the array. Hint: You can use the method you created in step 2 to retrieve the array of answers.
Create a method called magic8Ball that will basically run the whole program. (2 point)
It should ask the user to enter a question for the 8 Ball, generate a random number, and pass that to one of the methods above to get a response.
You will call this magic8Ball method in the main method.
The method should be called within the do-while loop, and repeat if the user wants to run the program again or not.
here's what I have:
package magic8;
import java.util.Random;
import java.util.Scanner;
public class magic8Ball {
public static String[] get8BallAnswers() {
String[] ball;
return ball = new String[] {"Yes, of course!", "Without a doubt, yes.",
"You can count on it.", "For sure!", "Ask me later.", "I'm not sure.", "I can't tell you right now", "I'll tell you after my nap.", "No way!", "I don't think so.", "Without a doubt, no.", "The answer is clearly No."};
}
public static void main(String[] args) {
boolean run = true;{
while (run) {
magic8Ball();
System.out.println("Do you want to try again, yes or no?");
Scanner scnr = null;
String go = scnr.nextLine();
go = go.toLowerCase();
if (go.equals("n")) {
System.out.println("Goodbye");
run = false;
}
if (go.equals("no")) {
System.out.println("Goodbye");
run = false;}
}
}
}
public static void magic8Ball() {
Scanner input = new Scanner(System.in);
String response;
System.out.println("Please ask me a question.");
response = input.nextLine();
Random gen = new Random();
int pick = gen.nextInt(ball.length);
System.out.println(ball[pick]);
return;
}
}
I can't get the random number generator to pass a integer into the array ball to get a response.
Try this
private static Scanner scanner = new Scanner(System.in);
private static String[] get8BallAnswers() {
return new String[] {"Yes, of course!", "Without a doubt, yes.", "You can count on it.",
"For sure!", "Ask me later.", "I'm not sure.", "I can't tell you right now",
"I'll tell you after my nap.", "No way!", "I don't think so.",
"Without a doubt, no.", "The answer is clearly No."};
}
private static String get8BallAnswers(int num) {
return get8BallAnswers()[num];
}
public static void main(String[] args) {
while (true) {
magic8Ball();
System.out.println("Do you want to try again, yes or no?");
if (scanner.nextLine().toLowerCase().contains("n")) {
System.out.println("Goodbye");
break;
}
}
}
private static void magic8Ball() {
System.out.println("Please ask me a question.");
scanner.nextLine();
System.out.println(get8BallAnswers(new Random().nextInt(get8BallAnswers().length)));
}

Parse Input and Determine Type of Data

I want to take input from user and then want to find is it Integer, float or something else. Till now I am using Scanner class for that. Like Scanner scan1=new Scanner(System.in);
String st= scan1.next(); and then I am trying to parse that input (st) in int and float respectively. But with this approach I am not able to satisfy the "else" condition. i.e. when input is neither string, int nor float.
Below is the code I tried :-
public String checkInput() {
String statement = "This input is of type ";
String inputType;
Scanner scan1 = new Scanner(System.in);
String st = scan1.next();
scan1.close();
inputType = st.getClass().getSimpleName();
try {
Float numFloat = Float.parseFloat(st);
inputType = numFloat.getClass().getSimpleName();
} catch (NumberFormatException e) {
}
try {
Integer numInt = Integer.parseInt(st);
inputType = numInt.getClass().getSimpleName();
} catch (NumberFormatException e) {
}
return statement + inputType;
}
here I am not able to decide how should I place else condition to check the input is neither string,float nor integer.
Here's how I would restructure your code. I'll explain the changes below:
private static final String STATEMENT = "This input is of type ";
public static String checkInput(Scanner scanner) {
if (scanner.hasNextFloat()) {
return STATEMENT + Float.class.getSimpleName();
else if (scanner.hasNextInt()) {
return STATEMENT + Integer.class.getSimpleName();
}
return STATEMENT + "UNKNOWN";
}
First, we pulled statement out into a constant, since it's not being changed.
Second, we pass the Scanner in as a parameter, rather than constructing a new one. There are a number of reasons to prefer this, but the principle one is that you should avoid creating multiple Scanner instances reading from System.in - generally you'll create such a Scanner in your main() method and pass it off to the methods and classes that need to use it.
Next, rather than reading from the scanner directly, we use the has*() methods to inspect the scanner's state without advancing it. This changes the semantics of checkInput(), because when it returns the input being inspected is still in the scanner, but that's more consistent with a method named check...() - it should inspect, not change state. Because your implementation calls .next() you lose the actual provided input, which is presumably undesirable.
Finally, we return from inside each block, rather than setting a temporary inputType variable and returning it at the end.
Your main() method might now look like this:
public static void main(String[] args) {
// using try-with-resources so we don't have to call .close()
try (Scanner scanner = new Scanner(System.in)) {
System.out.println(checkInput(scanner));
String input = scanner.next(); // this actually advances the scanner
System.out.println("You input: " + input);
}
}
Taking it further, you might prefer to have checkInput() return a Class<?> rather than a String, and then construct your statement separately. This would allow you to handle the inputs differently. For example:
public static Class<?> inputType(Scanner scanner) {
if (scanner.hasNextFloat()) {
return Float.class;
else if (scanner.hasNextInt()) {
return Integer.class;
}
// add other types as needed
return String.class;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
Class<?> inputType = inputType(scanner);
String input = scanner.next();
System.out.println("You input: " + input);
if (inputType.equals(Integer.class)) {
System.out.prinln("That's a valid integer!");
}
}
}
All that said, we're very much reinventing the wheel here. The "right" way to use Scanner is to use the typed methods directly - e.g.:
if (scanner.hasNextInt()) {
int value = scanner.nextInt();
}
This avoids needing to do any manual type checking or similar busywork - just let Scanner do the validation for you.

can't pass user input to main in method call

I am trying to write a simple program where user enters username and password at the command line. Program check user input if valid if yes, it displays Welcome whatever the name is. Program also check password valid. I couldn't find a way to call checkCommandLine in main and pass user input to it. Any advise?
public class HelloWorld3 {
public static boolean checkCommandLine(String [] args){
if (args.length == 1)
{
//If the string is blank “ “ then display error message
if (args[0].trim().isEmpty())
{
System.out.println("args[0] is null");
return false;
}
return true;
}
//If args does not contain a string then display an error message
else if (args.length == 0)
{
System.out.println("args[0] doesn't contain string");
return false;
}
return true;
}
public static final String Password = "abc123";
public static boolean checkPassword(String uPassword){
if (uPassword.equals(Password)){
return true;
} else {
System.out.println("Password invalid");
return false;
}
}
public static void main (String[]args){
//to receive the command line arguments
//call checkCommandLine
//if all ok the say welcome username
if (checkCommandLine(new String[] {"A", "B"})){
System.out.println("Welcome" + " " + "A");
}
//call checkPassword
//if valid then say from within main, your password is good
if (checkPassword("abc123")){
System.out.println("Your password is good");
}
//if not ok, then say password invalid
}
}
In the main method you can pass the command line arguments like this:
public static void main (String[]args){
checkCommandLine(args);
....
}
For passing the command line arguments you can refer http://www.javatpoint.com/command-line-argument
You can pass the args of main method just like Agrawal did.
If so, you can execute it from cmd as follows
java HelloWorld3 yourID abc123
else use Scanner to get the input during your code

How to access input variable from another class? java

Trying to get the 1st class to recognize what the user inputs in the 2nd class. Any ideas as to what is going wrong here? The 2nd class works fine, but when i try to call 'input' from the main class, it says that 'input' cannot be resolved. Any suggestions and pointers much appreciated. Thanks for your time.
1st class:
public class Filter {
public static void main(String[] args) throws IOException {
BufferedReader in4 = new BufferedReader(new StringReader(automata.input));
String s = input.readLine();
while (automata.UserInput()==true){
if (automata.accepts(s)) System.out.println(s);
s = input.readLine();
}
}
}
2nd class:
public class automata extends Filter {
public static String input;
public static boolean UserInput() {
System.out.println("Please enter test data: ");
Scanner user_input = new Scanner(System.in);
input = user_input.next();
if (accepts(input) == true){
System.out.print("works");
return true;
} else {
System.out.println("Problem");
return false;
}
}
2nd class should look like:
public class Automata { // we use upper case for class names
public String input; // or better private and use a get-method
public Automata() {} // constructor
public boolean readUserInput() { // lower case here
System.out.println("Please enter test data: ");
Scanner user_input = new Scanner(System.in);
String nextInput = user_input.next();
input += nextInput; // otherwise you overwrite your current input
/*if (accepts(input) == true){
System.out.print("works");
// return true;
} else {
System.out.println("Problem");
return false;
}*/
// It is a terrible idea to return every time a single word is read
// rather read the whole String and then check if it is accepted
if (accept(input)) // whole String is checked
return true;
return false;
}
// in case the input variable is private
public String getInput() {
return input;
}
}
And then you have to access the class in this way:
public class Filter {
public static void main(String[] args) throws IOException {
Automata automata = new Automata();
if (automata.readUserInput()) {
// BufferedReader in4 = new BufferedReader(new StringReader(automata.getInput())); or automata.input in case it is public
// I don't understand why you want to read the input here again step by step
// rather read the whole input here
String userInput = automata.getInput();
}
}
}
You are confused with two different things: Class and Object. The Object is an Instance of the Class. Without understanding this you cannot understand what is wrong here.
Calling, for example Automata automata = new Automata() creates new Object of the class Automata.
"Extends" never helps you to get to the variables. It may help you to extend the current class and to use the methods that have been implemented in parent class, but you can never get to the pointers on the address spaces of that parent class.
To access a variable of another object you should declare public getter method for that variable in that class.
I think you need to replace
String s = input.readLine();
by
String s = in4.readLine(); in Filter class.
as readLine() is a method of BufferedReader Class
Try to rename the name of BufferedReader in input like this:
BufferedReader input = new BufferedReader(new StringReader(automata.input));
I think you have a typo..
Change input in the 1st class to in4.
'input' variable is declared in the 2nd class and you are trying to access it in the 1st class which is really impossible.
In class Filter, You do not have any member named input, due to which compile time exception is coming at input.readLine();.
From the context of your program, it appears that in4 should be used instead of input.
public class Filter {
public static void main(String[] args) throws IOException {
BufferedReader in4 = new BufferedReader(new StringReader(automata.input));
String s = in4.readLine();
while (automata.UserInput()==true){
if (automata.accepts(s)) System.out.println(s);
s = in4.readLine();
}
}
}

How to fix a word requesting program?

I created a JAVA code, and I don't have any errors, but when I run the code, the output does this:
Enter a word: Thank you for entering a word! And it does not let me enter anything, when I intend for the code to let me enter a word, then it checks if it is a word, and gives the answer if it is a word, or none if it isn't. (It is my first time asking on this site) Here's the code:
package files;
import java.util.Scanner;
public class Testprinter {
static boolean myBoolean = false;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args){
String usersInput;
while(myBoolean != true)
{
System.out.print("Enter a word: ");
usersInput = userInput.toString();
myBoolean = checkInput(usersInput);
}
checkifComplete();
}
public static boolean checkInput(String usersInput){
if(usersInput == (String)usersInput)
{
return true;
} else { return false; }
}
public static void checkifComplete(){
if(myBoolean = true){
System.out.print("Thank you for entering a word!");
}
}
}
This line is wrong:
if (usersInput == (String)usersInput)
It should be:
if (usersInput.equals(usersInput))
In Java, strings (and in general: all objects, that is all types that are non-primitive) must me compared using the equals() method, which tests for equality. The == operator is fine for testing equality between primitive types, but for objects it tests for identity - a different concept, and 99% of the time, not what you want.
And besides, you're comparing a string with itself! it'll always return true, I'm quite sure that's not what you want to do… notice that the parameter must have a different name, currently it's called just like the attribute. Perhaps this is what you meant?
public static boolean checkInput(String input) {
return usersInput.equals(input);
}
You forgot scanner.nextLine(); thats reason its not asking you enter anything.
Instead of usersInput = userInput.toString();
Use:
String usersInputStr = scanner.nextLine();
Follow this link - for how to use scanner: How can I read input from the console using the Scanner class in Java?
Your issue is using userinput.toString(), when you should be using usersInput = userInput.next();. You are currently retrieving the string representation of the scanner, not getting a word.
Corrected main:
public static void main(String[] args){
String usersInput;
while(myBoolean != true)
{
System.out.print("Enter a word: ");
usersInput = userInput.next();
myBoolean = checkInput(usersInput);
}
checkifComplete();
}

Categories