Skip to main content

Next Line Doesn't Work

1 reply [Last post]
redwall1521
Offline
Joined: 2012-11-03
Points: 0

I'm a beginner at programming, so if you could stay to the basics that would be great. Thanks!

So my program is:

import java.util.*;

public class LineSample
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
int x;
String name;
System.out.println("Enter a value for x.");
x = scan.nextInt();
System.out.println("Enter your name.");
name = scan.nextLine();
}
}

When I compile, there are no errors. However, when I run, I am allowed to input a value for x, but the program skips over the part for reading in a value for the string "name".

When I edited the program and copied the two lines

System.out.println("Enter a value for x.");
x = scan.nextInt();

over to the end of the program, I was able to input a string (which I assumed was stored in "name") and an integer for "x".

Why does it work one way and not the other?

(This is not my real program, but that program requires that the integer is read in first, so I am stuck right now)

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
shingnpr
Offline
Joined: 2012-09-21
Points: 0

x = scan.nextInt(); and name = scan.nextLine(); are two different scenario because x case user expected to give some integer input and Scanner expected to read it while in later case if you have multi line input (reading from file)then you are going to read it from scan object and but here program is not expecting any input from user hence control check in Scan object if there is anything on next line then read and print else print null as is happening in your case.

if you other methods of Scanner object you won't be facing similar problem check it out.
I have done and its working fine.

Use String name = scan1.next(); rather than scan.nextLine();

It will work as per you assumption.