将字符读入数组

时间:2013-11-14 23:40:52

标签: java arrays input char

我有以下代码需要从用户那里获取10个字符并以相反的顺序打印出来。我似乎无法通过Scanner的这一个语法错误。我怎样才能一次输入一个字符?以下是我到目前为止的情况:

import java.util.Scanner;

public class ReverseOrder
{
   //-----------------------------------------------------------------
   //  Reads a list of char from user and prints in reverse.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Scanner scan = new Scanner (System.in);

      char[] letters = new char[10];

      System.out.println ("The size of the array: " + letters.length);
      for (int index = 0; index < letters.length; index++)
      {
         System.out.print ("Enter number " + (index+1) + ": ");
         letters[index] = scan.nextchar(); //doesnt like this line
      }

      System.out.println ("The numbers in reverse order:");

      for (int index = letters.length-1; index >= 0; index--)
         System.out.print (letters[index] + "  ");
   }
}

4 个答案:

答案 0 :(得分:2)

您也可以在不使用循环的情况下以相反的顺序打印出来:

System.out.println("The numbers in reverse order:");
System.out.println(new StringBuilder(new String(letters)).reverse())

答案 1 :(得分:1)

不幸的是,nextChar()不是一种方法。这可以使用next().charAt(0)来解决!

public class ReverseOrder
{
    //-----------------------------------------------------------------
    //  Reads a list of char from user and prints in reverse.
    //-----------------------------------------------------------------
    public static void main (String[] args)
    {
      Scanner scan = new Scanner (System.in);

      char[] letters = new char[10];

      System.out.println ("The size of the array: " + letters.length);
      for (int index = 0; index < letters.length; index++)
      {
         System.out.print ("Enter number " + (index+1) + ": ");
         letters[index] = scan.next().charAt(0);

      }

      System.out.println ("The numbers in reverse order:");

      for (int index = letters.length-1; index >= 0; index--)
         System.out.print (letters[index] + "  ");
    }
}

答案 2 :(得分:1)

您可以在您的情况下使用:

letters[index] = scan.nextLine().charAt(0);

替代scan.nextchar();

答案 3 :(得分:0)

char c = scan.nextLine()。charAt(0);

它必须是charAt(0)而不是charAt(索引),因为他总是想要第一个字母。