【问题标题】:Why am I getting an exception in thread main error?为什么我在线程主错误中出现异常?
【发布时间】:2013-12-06 17:20:55
【问题描述】:
import java.util.Scanner;

public class ReverseOrder
{

    char input;

   public static void main (String[] args)
   {


       Scanner reader = new Scanner (System.in);

       char [] ch = new char[5];


      System.out.println ("The size of the array: " + ch.length);

      for (char index = 0; index < ch.length; index++)
      {
         System.out.print ("Enter a char " + (index+1) + ": ");
         ch[index] = reader.next().charAt(0);
      }

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

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

}

【问题讨论】:

  • 什么异常,堆栈跟踪告诉你什么行号?不要让我们猜测!
  • 我是 Java 新手。我不知道在这里做什么。如果不嫌麻烦的话,能不能复制粘贴到eclipse里?
  • Collections.reverse(Arrays.asList(array));
  • 编写一个程序,将 5 个单个字符而不是数字作为输入并以相反的顺序输出它们
  • 这是我在线程 "main" java.lang.ArrayIndexOutOfBoundsException: 65535 at ReverseOrder.main(ReverseOrder.java:39) 中得到异常的错误

标签: java multithreading exception main


【解决方案1】:

您正在遭受char 溢出。

主要问题在于你的循环......

for (char index = 0; index < ch.length; index++)

for (char index = (char) (ch.length-1); index >= 0; index--)

使用char。尝试将它们更改为使用int,例如...

for (int index = 0; index < ch.length; index++)

for (int index = (ch.length-1); index >= 0; index--)

【讨论】:

  • 哇哦。太感谢了。一开始我并没有意识到,但这完全有道理。我很感激谢谢:)
【解决方案2】:

问题是您将char 用于您的for loops

改成

for (int index = 0; index < ch.length; index++)

for (int index = ch.length - 1; index >= 0; index--)

【讨论】:

    【解决方案3】:

    打印字符数组时。

    您应该进行以下更改:

    改变

    for (char index = (char) (ch.length-1); index >= 0; index--)
    

     for (int index =  ch.length-1; index >= 0; index--)
    

    打印示例如下:

    The size of the array: 5
    Enter a char 1: 1
    Enter a char 2: 2
    Enter a char 3: 3
    Enter a char 4: 4
    Enter a char 5: 5
    The numbers in reverse order:
    5  4  3  2  1  
    

    【讨论】:

    • 感谢您抽出宝贵时间提供帮助。真的很感激。这很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2013-12-09
    • 2017-04-20
    • 1970-01-01
    相关资源
    最近更新 更多