PDA

View Full Version : my program is not asking me what my fav color is


raptrex
01-31-2009, 10:07 PM
i get no error but my program should be asking me what my favorite color is
import java.util.Scanner;

public class Assignment2
{
public static void main (String [] args)
{
String firstName, middleName, lastName;
int age, luckyNumber;
String color;

Scanner keyboard = new Scanner(System.in);
System.out.println("What is your first name?");
firstName = keyboard.nextLine();
System.out.println("What is your middle name?");
middleName = keyboard.nextLine();
System.out.println("What is your last name?");
lastName = keyboard.nextLine();
System.out.println("How old are you?");
age = keyboard.nextInt();
System.out.println("What is your lucky number?");
luckyNumber = keyboard.nextInt();
System.out.println("What is your favorite color?");
color = keyboard.nextLine();

String fullName = firstName + " " + middleName + " " + lastName;
System.out.println("A story about " + fullName + ":");
String fullNameCaps = fullName.toUpperCase();
char firstInitial = firstName.charAt(0);
char middleInitial = middleName.charAt(0);
char lastInitial = lastName.charAt(0);
System.out.println("\t" + fullNameCaps + " is " + firstInitial + middleInitial + lastInitial);
System.out.println("\t" + firstInitial + middleInitial + lastInitial + "'s favorite color is " + color + ", and " + firstName + " " + lastInitial + ". is " + luckyNumber);
}
}

Fou-Lu
02-01-2009, 02:58 AM
This tends to be a poorly documented part of scanner.
Its been awhile since I've used java cmd, but I believe you simply need to clear out the left whitespaces on the buffer after the nextInt calls. This is because nextInt ignores whitespace separator and is left on the scanner buffer. When you're call to nextLine processes, it has an available whitespace character which is removed and assumed as you're input line. By 'removed', I mean its still on the scanner stack, but the scanner pointer has stepped to a location past the whitespace as opposed to before it.
After you're lucky number nextInt call, add a keyboard.nextLine(), this will remove the trailing whitespace separator and allow you're next call to keyboard.next* to request input.

This is why I always stick with nextline and use parseint where necessary. I hate having to worry about the scanner buffer.