简体   繁体   中英

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).

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)

I am new to Java and would appreciate help, thanks in advice.

That's not how arrays work. Change String word[] = {}; to String word[] = new String[10];

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

It is also a good idea to move Scanner input = new Scanner(System.in); outside of the for loop. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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