【问题标题】:trying to set a set of strings into a 2d array as chars, in java试图在java中将一组字符串设置为一个二维数组作为字符
【发布时间】:2021-09-23 20:06:19
【问题描述】:
import java.util.*;
import java.io.*;
import java.math.*;

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
class Solution {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int w = in.nextInt(); // width of the strings
        int h = in.nextInt(); // number of strings
        char[][] answer = new char[w][h];
        if (in.hasNextLine()) {
            in.nextLine();
        }
        for (int i = 0; i < h; i++) {
            String line = in.nextLine();
            for(int j = 0; j < w; j++){
                answer[i][j] = line.charAt(j);
                System.out.print(answer[i][j]);
             }
        }
    }
}

//抛出一个异常 (.ArrayIndexOutOfBoundsException: Index 9 out of bounds for length 9) //bascially what im试图做它说例如输入是这样的:

3

3

...

...

...

//宽度为 3,高度为 3,我试图用字符串的字符填充数组 //我对 java 有点陌生,但我喜欢解决这样的难题,这个难题正在吞噬我

【问题讨论】:

  • 你的答案数组应该是高度,宽度。
  • char[][] 答案 = 新 char[h][w];你可以创建高度,宽度的字符数组

标签: java char


【解决方案1】:

不是 100% 确定你在问什么,但我猜你正在寻找这样的东西:

        for (int i = 0; i < h; i++) {
            String line;
            while (true) {
                line = in.nextLine();
                if (line.length() == w)
                    break;
                else
                    System.out.println("Please enter a string of length "+w);
            }
            for(int j = 0; j < w; j++){
                answer[i][j] = line.charAt(j);
                System.out.print(answer[i][j]);
            }
            System.out.println();
        }

【讨论】:

  • 是的,这行得通,谢谢你们,我真的被卡住了,这设法避免了一个大问题的异常
  • @OwlGifter nps,如果你不介意接受这个作为答案,那么我可以获得甜蜜的 stackoverflow 积分:)
猜你喜欢
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
  • 1970-01-01
  • 2011-02-16
  • 2019-02-18
  • 2023-03-08
相关资源
最近更新 更多