鱼C论坛

 找回密码
 立即注册
查看: 2364|回复: 1

[已解决]如何将一维String裁剪并转存到二维String

[复制链接]
发表于 2022-3-20 13:42:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我想将输入的String[]按空格裁剪并存到二维的String[][]
下面是代码:

  1.     private static String[] studentIn = new String[100];
  2.     private static String[][] student = new String[100][100];

  3.     public static void inString() {
  4. //录入成绩
  5.         Scanner scan = new Scanner(System.in);
  6.         for (int i = 0; i < n; i++) {
  7.             studentIn[i] = scan.nextLine();
  8.         }
  9.     }
  10.    
  11.     public static void handle() {  
  12. //按空格裁剪并转存
  13.         for(int i=0;i<n;i++)
  14.         {
  15.             for(int j=0;j<6;j++)
  16.             {
  17.                 student[i][j]= studentIn[i].split("\\s+");
  18.             }
  19.         }
  20.     }
复制代码

但是这样做会提示不兼容的类型: String[]无法转换为String
最佳答案
2022-3-20 14:11:47
你不能把一个字符串数组赋给字符串,通过 split 方法得到的是一个字符串数组,

而 二维数组 里面的 第二维 的元素为 字符串,你应该把 字符串数组 赋给 二维数组 第一维 的元素,

故对你的代码修改如下:

  1.     private static String[] studentIn = new String[100];
  2.     private static String[][] student = new String[100][100];

  3.     public static void inString() {
  4. //录入成绩
  5.         Scanner scan = new Scanner(System.in);
  6.         for (int i = 0; i < n; i++) {
  7.             studentIn[i] = scan.nextLine();
  8.         }
  9.     }
  10.    
  11.     public static void handle() {  
  12. //按空格裁剪并转存
  13.         for(int i=0;i<n;i++)
  14.         {
  15.                 student[i]= studentIn[i].split("\\s+");             # 这里把 [j] 去掉,内层循环也不要
  16.         }
  17.     }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-3-20 14:11:47 | 显示全部楼层    本楼为最佳答案   
你不能把一个字符串数组赋给字符串,通过 split 方法得到的是一个字符串数组,

而 二维数组 里面的 第二维 的元素为 字符串,你应该把 字符串数组 赋给 二维数组 第一维 的元素,

故对你的代码修改如下:

  1.     private static String[] studentIn = new String[100];
  2.     private static String[][] student = new String[100][100];

  3.     public static void inString() {
  4. //录入成绩
  5.         Scanner scan = new Scanner(System.in);
  6.         for (int i = 0; i < n; i++) {
  7.             studentIn[i] = scan.nextLine();
  8.         }
  9.     }
  10.    
  11.     public static void handle() {  
  12. //按空格裁剪并转存
  13.         for(int i=0;i<n;i++)
  14.         {
  15.                 student[i]= studentIn[i].split("\\s+");             # 这里把 [j] 去掉,内层循环也不要
  16.         }
  17.     }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-15 05:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表