Why does it not ask me for input? - java

import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner name = new Scanner(System.in); ## I am asking for input form user but it does not take imput
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
}else System.out.println("Well good meet");
}
}
Why does the program run the else and not ask for my input?

You should read your input by using scanner.nextLine():
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
if (name.equals("me") || name.equals("Me"))
{
System.out.println("Well, good for you smartass.");
} else {
System.out.println("Well good meet");
}
scanner.close();

You merely created a Scanner but did not tell it to read something from the standard input. You can do that by calling scanner.next() to read a token scanner.nextLine() to read a line, etc. As well you are comparing a Scanner to a String in the if-statement.
import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner s = new Scanner(System.in);
String name = s.next(); // get the token
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
} else System.out.println("Well good meet");
}
}

You've only created an instance of the Scanner object. You need to invoke a method such as Scanner#nextLine() to read input and then compare the read value to "me" or "Me".
Example:
Scanner name = new Scanner(System.in);
String input = name.nextLine();
if (...) // Compare input to something here.
You might want to use String#equalsIgnoreCase for case-insensitive matching too.

Related

How to make java scanner accept more than one string input?

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans = "yes";
while (ans.equals("yes"))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}
Use the or operator in your expression
while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))
{
System.out.print("Test ");
ans = in.nextLine();
}
But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.
Don't compare the user input against a value as loop condition?!
Respectively: change that loop condition to something like
while(! ans.trim().isEmpty()) {
In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).
You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.
Using ArrayList, your code could look like this:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> positiveAnswers = new ArrayList<String>();
positiveAnswers.add("yes");
positiveAnswers.add("sure");
positiveAnswers.add("y");
Scanner in = new Scanner(System.in);
String ans = "yes";
while (positiveAnswers.contains(ans))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

Both next() and nextLine() not helping to store name with spacing

I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.
I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.
import java.io.IOException;
import java.util.Scanner;
public class ScannerTest {
static String name;
static Scanner in = new Scanner(System.in);
static int choice;
public static void main(String[] args) {
while(choice != 5){
System.out.print("\nEnter Choice :> ");
choice = in.nextInt();
if(choice == 1){
try{
printName();
}
catch(IOException e){
System.out.println("IO Exception");
}
}
}
}
private static void printName()throws IOException{
System.out.print("\nEnter name :> ");
name = in.next();
//name = in.nextLine();
if (name != null){
System.out.println(name);
}
}
}
Try this instead: add name = in.nextLine(); after choice = in.nextInt();.
Then try replacing name = in.next(); with name = in.nextLine();
Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the \n. We then consume the rest of the string with nextLine().
The second nextLine() is then used to get your string parameters.
The problem is easy: when you prompt the user to enter his/her choice, the choice will be an int followed by a new line (the user will press enter). When you use in.nextInt() to retrieve the choice, only the number will be consumed, the new line will still be in the buffer, and, so, when you call in.nextLine(), you will get whatever is between the number and the new line (usually nothing).
What you have to do, is call in.nextLine() just after reading the number to empty the buffer:
choice = in.nextInt();
if (in.hasNextLine())
in.nextLine();
before to call name = in.next(); do this in = new Scanner(System.in);
the object need rebuild itself because already has value.
good luck

Looping in Java(Beginners)

I have to use a loop in my code so that when someone enters yes, they can re-enter their names as many times as they want, but I have no idea how to do this. Any help is appreciated, here is my code:
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
String reply = keyboard.nextLine();
if (reply == "yes")
{
}
}
}
This reply == "yes" is not how you compare Strings in Java. This compares there memory locations, not there contents (and it's unlikely there memory locations are going to be equal).
Instead you need to use reply.equals("yes") or if you don't care about doing a case comparison, you can use reply.equalsIgnoreCase("yes") instead
do {
// The remainder of your code...
} while (reply.equalsIgnoreCase("yes"));
Updated
You may also wish to have a read through The while and do-while statements and The for Statement, which covers the basics of looping in Java
Use a do-while loop:
public static void main(String[] args) {
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
do {
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
} while (keyboard.nextLine().equalsIgnoreCase("yes"));
System.out.println("Bye!");
keyboard.close();
}
}
use this
import java.util.*;
public class prob13 {
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get the user's name.
while(true){
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
String reply = keyboard.nextLine();
if(reply.equals("no"))
break;
}
}
}
The reason for this is to loop through as long as the answer is not no.
or you could use this if you want the answer to always be yes
import java.util.*;
public class prob13 {
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
String reply="yes";
//Get the user's name.
while(reply.equals("yes")){
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
reply = keyboard.nextLine();
}
}
}
I think this will work (untested):
public static Scanner keyboard = new Scanner(System.in); // global
public static void main(String [] args)
{
getName();
}
public static void getName()
{
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
rerun();
}
public static void rerun()
{
System.out.println("Would you like to enter another name? Please enter \"yes\" or \"no\".");
String reply = keyboard.nextLine();
if (reply.equals("yes")) getName();
else System.exit();
}
}
First we call the getName() method and run through that once. Then we make a call to the rerun() method. This method will test if we want to re-run the program. If the user types in "yes", then we repeat the whole process. If we type in anything besides "yes", the program quits.
Besides the fact that your code is unfinished, the only real problem with your code is that you try to compare strings with the == operator. See MadProgrammer's answer as to why that is wrong.
The simplest (and probably clearest) way is to wrap what you want to repeat in a do-while statement:
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
String reply;
do {
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
reply = keyboard.nextLine();
} while ("yes".equals(reply));
}
}
The reply variable must be declared before the block, because it is accessed in the loop condition (a variable is only visible in the block it is declared in, so if reply were declared in the loop, it would not be available to the loop condition).
I changed the loop condition because the == operator compares Strings by reference, i.e. it will check whether both sides point to the same String object. The equals method, in contrast, checks that the content of the Strings is equal (i.e. they contain the same characters in the same order).

Whats wrong with my User Input Code?

Everytime I use this code:
import java.util.*;
public class Main{
public static void main (String args []){
System.out.println("What is your name?");
Scanner name = new Scanner (System.in);
System.out.println("Hello," + name);
}
}
It just gives me random letters like:
Hello,java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false]
Please someone help.
Because what you are doing is actually just printing out the Scanner's toString method since in your code, the object name is actually an instance of Scanner, which is NOT a string.
You need to call the method to actually read the user input.
What you need to do is do something like this
import java.util.*;
public class Main{
public static void main (String args []){
System.out.println("What is your name?");
Scanner scanner = new Scanner (System.in);
String name = scanner.next();
System.out.println("Hello," + name);
}
}
Scanner name = new Scanner (System.in);
Using this you have created an scan reference. Use this to read the name like
String str = name.next();
Read about Scanner class for more details.
You are printing reference of Scanner.
If you want to input an integer, Write
Scanner in = new Scanner(System.in);
int n = in.nextInt();
If you want to input a string, write
Scanner in = new Scanner(System.in);
String n = in.next();

String input in program

I can't find the answer in my book and it's an easy one but I'm missing something simple here.
I have a program where I ask the user "choose customer or employee C or E" Then after that I need to say if they picked C then do this or if they picked E do that.
I'm new and struggling so I know this is probably an easy thing but I'm not getting it.
Scanner in = new Scanner(System.in);
system.out.println("choose c or e: ");
if (in.equalsIgnoreCase("c"))
{
//do something
}
if (in.equalsIgnoreCase("e"))
{
// do something
}
what am I doing wrong here?
The Scanner isn't the actual input - you need to read the input from the scanner, e.g.
Scanner scanner = new Scanner(System.in);
// Note capital S - Java is case-sensitive
System.out.println("choose c or e: ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("c"))
...
Scanner has no method like equalsIgnoreCase(), this method is present in String. So using next() or nextLine() get a String and do what you want
Scanner in = new Scanner(System.in);
system.out.println("choose c or e: ");
String value = in.next();
if (value.equalsIgnoreCase("c"))
{
//do something
}
if (value.equalsIgnoreCase("e"))
{
// do something
}
in is a Scanner, not a string. Use in.next()

Categories

Resources