二维数组输入

时间:2014-11-23 19:36:27

标签: java arrays

我有一个功课是用户必须在一个数组内输入10个字,但我找不到办法做到这一点

例如,如果用户输入以下单词:

 abigail
 wilbert
 steve
 android
 lucky
 hello
 help
 htc
 matrix
 kim

当我打印数组

时输出应该是
abigail
 wilbert
 steve
 android
 lucky
 hello
 help
 htc
 matrix
  kim

这是我的程序

import java.io.*;
class example
{
public static void main(String[] args) throws IOException
{
    matrix obj=new matrix();
    obj.practice();
}
}
class matrix
{
void practice() throws IOException
{
    InputStreamReader isr=new InputStreamReader(System.in);
    BufferedReader br=new BufferedReader(isr);
    char A[][]=new char[10][10];
    int r,c,i,j;
    String x;
    char b;
    for(r=0;r<10;r++)
    {
        System.out.println("Enter the "+(r+1)+" word");
        x=br.readLine();
        for(c=0;c<x.length();c++)
        {
            A[r][c]=x.charAt(c);
        }
    }
    for(i=0;i<10;i++)
    {
        for(j=0;j<10;j++)
        {
                System.out.print(A[i][j]);
        }
    }   System.out.print("\n");


}

}

1 个答案:

答案 0 :(得分:0)

我不确定你为什么要使用多维数组。这是一个适合您的解决方案,演示了一些OO概念。

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;

public class StringArrayOfWords {

  //instance variables
  private ArrayList<String> lines = new ArrayList<>();
  private static StringArrayOfWords arr = new StringArrayOfWords();//declare object

    public static void main(String[] args) throws Exception {
        String [] printArray = arr.readFile();//use an array to hold contents of arr.readFile for easy printing
        System.out.println(Arrays.toString(printArray));//Arrays.toString will print the contents of an Array
    }

    //method to read a file and call on object 
    public String [] readFile() throws Exception{  
        //display a gui window to choose a file to read in
        JOptionPane.showMessageDialog(null, "Please choose a question file");        
        JFileChooser input = new JFileChooser();
        int a = input.showOpenDialog(null);
        String file = "";
        if (a == JFileChooser.APPROVE_OPTION) {
            File selectedFile = input.getSelectedFile();
            file = selectedFile.getPath();
        }

        //use file input to read in line one at a time
        FileInputStream fstream = new FileInputStream(file);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = br.readLine()) != null) {
            lines.add(line);
        }
        //convert ArrayList to array
        String[] arr = lines.toArray(new String[lines.size()]);

        return arr;
    }
}