1

我有以下代码需要从用户那里获取 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

4 回答 4

2

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

System.out.println("The numbers in reverse order:");
System.out.println(new StringBuilder(new String(letters)).reverse())
于 2013-11-15T00:07:26.107 回答
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] + "  ");
    }
}
于 2013-11-14T23:43:07.443 回答
1

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

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

作为 scan.nextchar() 的替代品;

于 2013-11-14T23:43:15.077 回答
0

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

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

于 2013-11-14T23:47:39.543 回答