-
Scanner Problems
I'm having trouble using the scanner class to simple read in values. I've simplified my program to basically just read in values and for some reason it still wont read in the title2 variable or actor variable... it just skips them. No doubt I'm making some schoolboy error in my code but could someone take a look and see if they can spot something, thanks.
Code:
import java.util.Scanner;
public class scanStuff
{
public static void main(String[] args)
{
String title, title2, artist, director, actor;
int playTime, numOfTracks;
Scanner scan = new Scanner(System.in);
System.out.print("Title: ");
title = scan.nextLine();
System.out.print("Artist: ");
artist = scan.nextLine();
System.out.print("Length: ");
playTime = scan.nextInt();
System.out.print("Number of tracks: ");
numOfTracks = scan.nextInt();
System.out.print("Title: ");
title2 = scan.nextLine();
System.out.print("Director: ");
director = scan.nextLine();
System.out.print("Length: ");
playTime = scan.nextInt();
System.out.print("Actor: ");
actor = scan.nextLine();
}
}
-
Your scan.nextInt() doesn't swallow the end of line token and you'll have to do this yourself. So every where you call scan.nextInt() call scan.nextLine() and discard the result. e.g., change this:
Code:
System.out.print("Number of tracks: ");
numOfTracks = scan.nextInt();
to this:
Code:
System.out.print("Number of tracks: ");
numOfTracks = scan.nextInt();
scan.nextLine(); // call this but don't extract the returned value.
-
Thanks a lot for the help
-