#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    3
    Rep Power
    0

    Angry Whats Wrong With My Code???


    Code:
    import java.util.Scanner;
    
    public class Main
    {
    public static void main(String args[])
    {
    Scanner S=new Scanner(System.in);
    
    System.out.println("Enter the first integer ");
    
    int i=S.nextInt();
    
    System.out.println("Enter the second integer "); 
    
    int j=S.nextInt(); 
    
    System.out.println("Enter the first character ");
    
    char ch1=S.next().charAt(0);
    
    System.out.println("Enter the second character ");
    
    char ch2=S.next().charAt(0); 
    
    System.out.println("Enter the first string "); 
    
    String str1=S.nextLine(); 
    
    System.out.println("Enter the second string"); 
    
    String str2=S.nextLine();
    
    OverloadCompare object=new OverloadCompare(); 
    
    object.Compare(i, j);
    
    object.Compare(ch1, ch2);
    
    object.Compare(str1, str2);
    
    S.close();
    }
    }

    When I execute the program, it asks for first, second integers and characters, but the first string asking is not asked, its just printed but I don't get to input it, only the second string can be inputed. Whats wrong ??
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,696
    Rep Power
    347
    You are having a problem with the Scanner class. When nextInt() is called and the Enter key is pressed, a newline character is left in the Scanner's buffer. The next call to nextLine() returns that newline character. To see print out what is read by the call to nextLine() following a call to nextInt().
    A fix is to call the nextLine() method after calling nextInt() to clear the newline character from the Scanner's buffer
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    3
    Rep Power
    0
    Originally Posted by NormR
    You are having a problem with the Scanner class. When nextInt() is called and the Enter key is pressed, a newline character is left in the Scanner's buffer. The next call to nextLine() returns that newline character. To see print out what is read by the call to nextLine() following a call to nextInt().
    A fix is to call the nextLine() method after calling nextInt() to clear the newline character from the Scanner's buffer

    thank you so much d00d. cheers

IMN logo majestic logo threadwatch logo seochat tools logo