简体   繁体   English

Java,基本数组错误

[英]Java, basic array error

I am trying to do a Java program that will let me input 10 words, and then the words should be repeated in reverse order (the last first etc). 我正在尝试做一个Java程序,该程序将允许我输入10个单词,然后应该以相反的顺序(最后一个等)重复这些单词。

This is my current code: 这是我当前的代码:

import java.util.Scanner;
import java.lang.String;

public class Words {

public static void main(String[] args){

String word[] = {};

for(int x = 0; x < 10; x+=1) {

System.out.println("Input any word");

Scanner input = new Scanner(System.in);
word = new String[] { input.next() };

      }

for(int y = 9; y >= 0; y-=1) {

System.out.println(word[y]);

      }
}}

It gives me the following error when trying to compile: 尝试编译时出现以下错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at Words.main(Words.java:21) 线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:Words.main处为9(Words.java:21)

I am new to Java and would appreciate help, thanks in advice. 我是Java的新手,希望能得到帮助,谢谢提供建议。

That's not how arrays work. 数组不是这样工作的。 Change String word[] = {}; 更改String word[] = {}; to String word[] = new String[10]; 改为String word[] = new String[10];

Also, change word = new String[] { input.next() }; 另外,更改word = new String[] { input.next() }; to word[x] = input.next() . word[x] = input.next()

It is also a good idea to move Scanner input = new Scanner(System.in); Scanner input = new Scanner(System.in);移动也是一个好主意Scanner input = new Scanner(System.in); outside of the for loop. for循环之外。 You should read up on how arrays work to make sure this doesn't happen again. 您应该阅读数组的工作原理,以确保不再发生这种情况。

You could try use an ArrayList to do this like so: 您可以尝试使用ArrayList这样做,如下所示:

import java.util.*;

public class HelloWorld
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        ArrayList al = new ArrayList();
        do{
            System.out.println("Enter word");
            String word = sc.nextLine();
            al.add(word);
            if(al.size()==10){
                System.out.println("Words in reverse order");           
                for(int i = al.size()-1; i>= 0; i--){
                    System.out.println(al.get(i));
                }
            }
        }while(al.size()<10);
    }
}

I think this answers your question properly. 我认为这可以正确回答您的问题。

All the best 祝一切顺利

Sean 肖恩

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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