String input in program - java

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()

Related

How to input characters using Classes and Objects

I'm making a java program that has to store data using classes and objects, My question is how do input characters like a name ( billy ) into my code.
Here is the class i did.
class bank
{
int AccountID;
int HolderName;
double AccountBalance;
}
And i'm assigning here
angel.AccountID = 7532;
angel.HolderName = 753; // angel
angel.AccountBalance = angelbalance;
I know that i can input integers using the following code
System.out.println("Set Balance for Angel: ");
int angelbalance = sc.nextInt();
My question is how do i input text/characters in a way (scanner) does with integer
Sorry for the bad explanation.
Do you mean getting the name input using the Scanner object? Because you've imported java.util.Scanner, you can do:
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
This will read the next line.
You can use (JOptionPane.showInputDialog) and it is easy to use if you want input from user
String name= JOptionPane.showInputDialog("Enter your name: "));
You need to either call the Scanner.nextLine() method or the Scanner.next() method to store String input such as a name like "Billy". Here is an example below:
//You can use the Scanner.next() method or the Scanner.nextLine() method to store Strings
Scanner scan = new Scanner(System.in);
System.out.println("Enter a name: ");
String billy = scan.next();
System.out.println("You entered: " + billy);
And here is your output:
Enter a name:
Billy
You entered: Billy
I'd check out the Scanner documentation here: https://docs.oracle.com/javase/8/docs/api/java/util/class-use/Scanner.html

Trying to break up a string into list

I'm trying to convert a String into a List. I'm getting the string by user input, but whenever I run my code, and it gives me this:
Enter a number: java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
This is my code
public class ch3_15 {
public static void main(String[] args) {
int compNum, user_hund, user_ten, user_one, comp_hund, comp_ten, comp_one;
String s;
//user input
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.toString();
//generating random number
compNum = (int) Math.random() * 1000;
System.out.println(s);
//finding the hundreds, tens, and ones place of the user number
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
}
}
This is not error. It is expected behavior since you used
Scanner input1 = new Scanner(System.in);
s = input1.toString();
...
System.out.println(s);
and toString() returns String representing of object on which this method was invoked (in this case instance of Scanner).
If you want to use that Scanner to read line from user you should write
s = input1.nextLine();
// ^^^^^^^^
Your problem is that you don't read the next String from the console, but rather convert the Scanner to a String, which you then print.
What you want to use is Scanner.nextLine(), instead of toString().
Also, this is not a runtime error, but simply a wrong output.
you should use scanner.nextLine() to read next line that use enters.
Your current code is printing the toString() method of the scanner object and that is not a runtime error and is an expected behaviour.
//user input
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.nextLine();
You are not advancing from your current line; the method to use in this case is nextLine() from the class Scanner; So the code would be something like:
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.nextLine();
String aux = s.toString(); // To return the string representation from the sc
nextLine() method from Java API 7 => This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.**/

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

Why does it not ask me for input?

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.

How do I make Java register a string input with spaces?

Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}

Categories

Resources