Scanner Stops Working and Println Problems, Why? - java

I'm using eclipse for this project. I've tried compiling in command prompt but the same problems happen. The scanner works until I get to "phone" and then it just seems to skip the user input and prints everything else on the same line.
I expect to store the users input into the assigned variables, and then print them out on separate lines.
I added sc.close; to see if that would help but it didn't. Some help would be greatly appreciated. Also my variable "address" isn't completely printed out.
I think I may be using Scanner incorrectly?
import java.util.Scanner;
public class ContactDisplay {
public static void main(String[] args) {
//Write a program that displays your name, address, and telephone number;
//create scanner
Scanner sc = new Scanner(System.in);
//Creates the variables;
String name;
String address;
String phone;
//Asks for name
System.out.print("What is your name? ");
//stores the name
name = sc.next();
//Asks and stores the address
System.out.print("What is your address? ");
address = sc.next();
//Asks and stores the phone number
//PROBLEM IS BELOW
System.out.print("What is your phone number? ");
phone = sc.next();
//Prints everything out
System.out.println(name);
System.out.println(address);
System.out.println(phone);
}
}
Here is a screenshot:

You should use 'sc.nextLine()' to scan string values, and you should use 'sc.nextInt' to scan integer values. If you press ctrl and space keys while typing a bunch of code it shows you the possible things you may want to write.

Related

How do i use scanner input from another method as a variable in another method

I have to refer to the users input name in the second method an I don't know if it is possible . What i have right prompts me to enter the name agin. also sorry if this is a dumb question i just started to code.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
getName(keyboard);
getRounds(keyboard,getName());
public static String getName(Scanner keyboard ) {
System.out.print("Welcome to ROCK PAPER SCISSORS. I, Computer, will be your opponent.\n");
System.out.print("Please type in your name and press return: ");
String name = keyboard.next();
System.out.print("\nWelcome " + name + ".");
return name;
}
public static int getRounds(Scanner keyboard, Sting getName) {
System.out.println();
System.out.print("\nAll right"+getname+ "How many rounds would you like to play?\n");
System.out.print("Enter the number of rounds you want to play and press return: ");
int rounds = keyboard.nextInt();
return rounds;
You are returning a reference to a String object from your getName method. Good.
But then you neglected to capture that returned value. Bad.
String name = getName( keyboard );
This is just like what you did when you captured the returned reference from new Scanner(System.in) and stored that reference in a variable named keyboard. (By the way, “keyboard” is not the best name there, “scanner” or “console” is more appropriate.)
Then pass that reference to your getRounds method.
getRounds( keyboard , name );
This is just like what you did when you pass keyboard to the same method.
Before posting here, study The Java Tutorials provided free-of-cost by Oracle Corp.

When user presses "enter" key or space enter then error message pops up

I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".

Strange output when I read from scanner

I'm trying to create a videoStore with the basic CRUD operation. For creating each movie I need to read the title, the year and the gender as below:
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
When I enter the addMovie option, I get this print on the console
(name: year:)
Can someone explain to me why it happens as above?
Here is the rest of the method:
static ArrayList<Movie> movies = new ArrayList<Movie>();
static Scanner in = new Scanner(System.in);
public static void InserirFilme() {
String name;
int year;
String gender;
boolean existe = false;
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
Movie movie = new Movie(name, year, gender);
for(Movie m: movies)
{
if(movie == m)
{
existe = true;
}
}
if(!existe)
{
movies.add(movie);
}
else
{
System.out.println("the movie already exists in the videoStore");
}
}
Calling next does not remove the line break, which means the next time you call InserirFilme the call to read the name can complete immediately. Use nextLine.
System.out.print("gender: ");
gender = in.nextLine();
(You probably mean "genre" instead of "gender" though)
Also, as mentioned in the comments, this check will never succeed:
if(movie == f)
You run this method in loop (right?)
The first call reads input correctly, but it leaves the linebreak in System.in after the last in.next().
On next call the name: is printed, then scanner reads an empty string from System.in because the linebreak already exists here.
And after thet the year: is printed on the same line because no new linebreaks are entered.
So you just have to insert another in.nextLine() after reading gender (or genre :) )
Or use nextLine() for read genre instead of next(), because genre might have more than one word.
But there are some disadvantages with using fake nextLine() to 'eat' linebreak - there might be another text which you doesn't process. It's a bad practice - to loose the data user entered.
It is better to read all the data from line, then validate/parse it, check isn't there some extra data, and if the data is invalid show notification and let him try to enter the right value.
Here are some examples how to deal with user input manually - https://stackoverflow.com/a/3059367/1916536. This is helpful to teach yourself.
Try to generalize user input operations:
name = validatedReader.readPhrase("name: ");
year = validatedReader.readNumber("year: ");
genre = validatedReader.readWord("genre: ");
where ValidatedReader is a custom wrapper for Scanner which could use your own validation rules, and could gently re-ask user after a wrong input.
It could also validate dates, phone numbers, emails, url's or so
For production purposes, it is better to use validation frameworks with configurable validation rules. There are a lot of validation frameworks for different purposes - Web, UI, REST etc...
when i enter the addMovie option, i get this print on the console (name: year:) can someone explain me why it happens i already searched a lot and i cant understand why :S
The way i understood your question is that you are getting the output (name: year: ) in a line and want it in seperate lines? In that case you simply can use System.out.println(String); instead of System.out.print(String). On the other hand you can also use "\n" whenever you want a linebreak within a String. Hope i could help you :).
Edit: If this was not an answer to your question, feel free to tell me and clarify your question :)
For String name you are using in.nextLine(); i.e the data entered on the entire line will be added to name string.
After "name: " is displayed, enter some text and press enter key, so that the year and gender fields will get correct values.
The code written is correct but you are not giving appropriate input through the scanner.
I recommend to use
String name = in.next();//instead of String name = in.nextLine();
You may instantiate Scanner Class differently for String and Integer type input. It works for me :)
Example:
static Scanner in1 = new Scanner(System.in);
static Scanner in2 = new Scanner(System.in);
Please use nextLine() for 'name' and 'gender'. It may contain more than one word. Let me know if it works.
Example:
System.out.print("name: ");
name = in1.nextLine();
System.out.print("year: ");
year = in2.nextInt();
System.out.print("gender: ");
gender = in1.nextLine();

How do I use java.util.Scanner with integers

I just started learning java and I want to make a simple program where it requests the persons
name, outputs the name then asks for the thier favorite number. It will then compare their number
to the number 6 and will output something depending on if the number is larger or smaller than 6.
I am getting a "String to int convert" error in Netbeans which has to do with the scanner.
Hopefully I am asking this correctly but how can I make the scanner pick-up integers?
Thanks
package javaapplication2;
import java.util.Scanner;
import java.lang.String;
public class JavaApplication2 {
public static void main(String[] args) {
// Creating an instance of the scanner class.
// Gets name and numbers.
Scanner getName = new Scanner(System.in);
Scanner getNumber = new Scanner(System.in);
//Holds name and number
String userName;
int userNumber;
// Asks for the users name.
// Holds name in userName.
System.out.println("What is your name?");
userName = getName.nextLine();
//Reponds with the users name.
System.out.println("Hello" + userName + "!");
//Asks for favorite number.
// Holds number in userNumber.
System.out.println("What is your favorite number?");
userNumber = getNumber.nextLine();
// Checks if users number is larger than 6.
if (userNumber > 6) {
// Stuff goes here.
}
}
}
You should use only one Scanner for one input stream:
Scanner in = new Scanner(System.in);
And after that you should use it's methods to get integers:
String name = in.nextLine();
int number = in.nextInt();
To be sure, you should read the documentation for Scanner:
Scanner
Scanner::nextLine
Scanner::nextInt
This might help: Javadoc page for Scanner.

Getting accurate int and String input

I am having trouble reading in strings from the user after reading in an int. Essentially I have to get an int from the user and then several strings. I can successfully get the user's int. However, when I begin asking for strings (author, subject, etc...), my scanner "skips" over the first string input.
For example, my output looks like this:
Enter your choice:
2
Enter author:
Enter subject:
subject
As you can see, the user is never able to enter the author, and my scanner stores null into the author string.
Here is the code that produces the above output:
String author;
String subject;
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter choice:");
choice = input.nextInt();
System.out.println("Enter author:");
author = input.nextLine();
System.out.println("Enter subject:");
subject = input.nextLine();
Any help would be greatly appreciated. Thank you!
-Preston Donovan
The problem is that when you use readLine it reads from the last read token to the end of the current line containing that token. It does not automatically move to the next line and then read the entire line.
Either use readLine consistently and parse the strings to integers where appropriate, or add an extra call to readLine:
System.out.println("Enter choice:");
choice = input.nextInt();
input.nextLine(); // Discard the rest of the line.
System.out.println("Enter author:");
author = input.nextLine();
This works perfectly.
Although while making previous programs like the one below it was not required. Can anyone explain this?
import java.util.Scanner;
public class Average Marks {
public static void main(String[] args) {
Scanner s = new Scanner ( System.in);
System.out.print("Enter your name: ");
String name=s.next();
System.out.print("Enter marks in three subjects: ");
int marks1=s.nextInt();
int marks2=s.nextInt();
int marks3=s.nextInt();
double average = ( marks1+marks2+marks3)/3.0;
System.out.println("\nName: "+name);
System.out.println("Average: "+average);

Categories