1

im fairly sure the mistake I am making within this code is short sighted. so this program starts by getting the first name and last name of the user and storing them as independent strings. the next part is for the program to manipulate that value into getting the first initial of the first name, which is where im having my problem (I have little experience with the CharArray function and have spent enough independent research time for me to opt to asking here lmao)

import java.util.Scanner; //Needed for the Scanner class

public class NumericTypes {
    public static void main (String [] args) {
        //TASK #2 Create a Scanner object here
        //Reading from system.in
        Scanner keyboard = new Scanner(System.in); 
        //prompt user for first name
        System.out.println("Enter your first name: "); 
        //scans the next input as a double
        String firstName = keyboard.nextLine(); 
        //prompt user for last name
        System.out.println("Enter your last name: "); 
        //scans the next input as a double
        String lastName = keyboard.nextLine(); 
        //concatenate the user's first and last names
        String fullName = (firstName + " " + lastName);
        //print out the user's full name
        System.out.println(fullName);
        //task 3 starts here
        //get first initial from variable 'fullName'
        String firstinitial = fullName.CharAt(0);
        System.out.println("the first initial is: " + firstinitial);
    }
}

my desired output is for the last set of lines to display the first initial of the first name (user input). any help would be greatly, greatly appreciated

5
  • replace String firstinitial with char firstinitial Commented May 3, 2017 at 4:14
  • 2
    replace CharAt with charAt Commented May 3, 2017 at 4:14
  • and also wrap it with String.valueOf like this: String firstinitial = String.valueOf(fullName.charAt(0)); Commented May 3, 2017 at 4:18
  • first initial means you want the first character of the first name ? please give an example Commented May 3, 2017 at 4:30
  • Possible duplicate of How to convert a char array back to a string? Commented May 3, 2017 at 5:28

1 Answer 1

1

This can be done in two ways -:

1.) Replace String firstinitial with char firstinitial

2.) Wrap fullName.charAt(0) with String.valueOf like this: String firstinitial = String.valueOf(fullName.charAt(0));

Both will work just fine.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much for this contribution. it ended up being such an easy fix lol <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.