简体   繁体   中英

Why does this java toCharArray statement only work sometimes?

I'm having problems with the following code. Specifically, the 3 toCharArray statements. When I first ran the code, it worked fine, but running it again, I get the following error messages for all 3 lines

']' expected
illegal start of expression
not a statement

I realize I can have it print the initials by just changing them to char[] and putting the [0] call in the print statement, but I'm curious why the code only works about half the time.

Thanks!

import java.util.Scanner;

public class Initials {
    public static void main(String[] args) {

        Scanner names = new Scanner(System.in);

        System.out.print("What is your first name? ");
        String first = names.nextLine();

        System.out.print("What is your middle name? ");
        String middle = names.nextLine();

        System.out.print("What is your last name? ");
        String last = names.nextLine();

        System.out.format("Your name is %s %s %s %n",first,middle,last);

        char[0] Finitial = first.toCharArray();
        char[0] Minitial = middle.toCharArray();
        char[0] Linitial = last.toCharArray();

        System.out.format("Your initials are %c %c %c",Finitial,Minitial,Linitial);
    }
}

char[0] isn't a valid type for the Finitial variable. The only time you get something like char[0] is in:

char[] x = new char[0];

Instead, you should use:

char firstInitial = first.toCharArray()[0];
// etc

Or in two stages:

char[] firstArray = first.toCharArray();
char firstInitial = firstArray[0];

This is illegal syntax:

char[0] Finitial = first.toCharArray();
char[0] Minitial = middle.toCharArray();
char[0] Linitial = last.toCharArray();

You want his instead:

char Finitial = first.toCharArray()[0];
char Minitial = middle.toCharArray()[0];
char Linitial = last.toCharArray()[0];

BTW: Java naming conventions demand that you start your local variable names with a lowercase letter. Use camel case like this:

char firstInitial = first.toCharArray()[0];
char middleInitial = middle.toCharArray()[0];
char lastInitial = last.toCharArray()[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM