1

我必须编写一个程序来读取用户(键盘扫描仪)的 10 个名称并将它们存储在一个数组中。然后循环遍历数组并以大写形式显示名称(使用 for each 循环将它们全部显示)。我该怎么做?目前我有:

import java.util.Scanner;

public class Names
{
    public static void main(String[] args) throws Exception
    {
        Scanner nameScan = new Scanner(System.in);
        String[] names = new String[10];
        String[] namesUpper = new String[10];

        System.out.print("Enter a name : ");
        names=nameScan.next(); 


        namesUpper=names.toUpperCase();
        System.out.println("Names in upper case: "+namesUpper);
    } 
}

到目前为止,我有这个,但仍然没有工作。请问我哪里错了?谢谢

import java.util.Scanner;

    public class NamesReAD
    {
        public static void main(String[] args) throws Exception
        {
            Scanner nameScan = new Scanner(System.in);
            String[] names = new String[10];


            for (int i = 0 ; i < names.length ; i++) {
                System.out.print("Enter a name: ");
                names[i] = nameScan.nextLine().toUpperCase();
            }
            nameScan.close();
            System.out.println("Here is name"+names);
        }
    }
4

2 回答 2

1
for (int i = 0 ; i < names.length ; i++) {
    System.out.print("Enter a name: ");
    names[i] = nameScan.nextLine().toUpperCase();
}

除了 .toUpperCase(); 之外,本节都可以使用。它不会将名称更改为大写。

于 2012-11-04T20:53:06.647 回答
0

You'll need a for-loop to traverse the array(s) and put the appropriate data at each index. For instance,

for (int i = 0 ; i < names.length ; i++) {
    System.out.print("Enter a name: ");
    names[i] = nameScan.nextLine();
}

This will ask the user for a name 10 times, and will fill the names array with whatever the user inputs. Now, you don't really have to create a second array (namesUpper); you can just loop over names again and print names[i].toUpperCase() (or use a for-each loop as you suggested, but the idea is the same).


As you have it now, these two lines won't compile:

names = nameScan.next(); 
namesUpper = names.toUpperCase();

since 1) names is an array and nameScan.next() returns a string and 2) names has no method called toUpperCase.


EDIT: Or, you could just store the names as upper-case when you add them to the names array:

for (int i = 0 ; i < names.length ; i++) {
    System.out.print("Enter a name: ");
    names[i] = nameScan.nextLine().toUpperCase();
}

Then you wouldn't have to worry about anything when you print the contents of the array.

于 2012-11-04T12:49:23.173 回答