1

so I am collecting information, namely 2 numbers and a string and processing them later on in my code. The numbers work fine and everything will work fine as long as I can get letter to output what letter the user input. Any help much appreciated. Just to be clear, when I say 'not working' I mean letter is blank, and the last line of code outputs :

The letter is

   Scanner sc = new Scanner(System.in);

    System.out.println("Enter two integers and a Letter ");

    int num1 = sc.nextInt();  

    int num2 = sc.nextInt(); 

    String s = sc.nextLine(); 




   System.out.println("s is of type " +  s.getClass().getName());   // s is a String

   System.out.println(s); //s has value of this

    char letter = s.charAt(0);  //Why isn't this working? 

    System.out.println("The letter is " + letter); //letter isn't showing up
  • What do you mean? Is there an error message? Are you sure that your string does not start with a whitespace character? – Arnaud Denoyelle Oct 30 '17 at 11:28
  • What do you mean it "isn't working"? – Carcigenicate Oct 30 '17 at 11:29
  • @Carcigenicate, I mean the last line of code, prints: The letter is With nothing after it, letter is empty in other words. – programmerssidds Oct 30 '17 at 11:36
  • @programmerssidds It's probably printing a whitespace character. – Carcigenicate Oct 30 '17 at 11:37
  • I was writing the answer but the question has been closed. Actually, the resulting String s ends up having a space. For example, if you enter `1 2 a` as an input, the value of `s` will be " a" (with a space before the `a`. That is why `charAt(0)` displays a space. You can solve it by displaying the last character instead of the first (`char letter = s.charAt(s.length() - 1)`). – Arnaud Denoyelle Oct 30 '17 at 11:38
  • Arnaud Denoyelle thank you so very much! **solved** – programmerssidds Oct 30 '17 at 11:43

0 Answers0