繁体   English   中英

为什么我收到变量未初始化错误?

[英]Why am I getting variable not initialized error?

我正在尝试将字符串中的所有字符转换为二维字符数组。 详情如下:

我的代码:

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        //System.out.println("Hello World");
        Scanner sc=new Scanner(System.in);
        int n,l=0;       //as you can see, n is initialized
        String x="";
        char[][] arr1=new char[10][10];
        if(sc.hasNextInt())
            n=sc.nextInt();
        for(int i=0;i<n;i++){
            if(sc.hasNextLine())
                x=sc.nextLine();
            //char[] arr=x.toCharArray();
            if(x.length()==n){
                   for(int j=l;j<arr1.length;j++){
                       for(int k=0;k<arr1.length;k++){
                           arr1[j][k]=x.charAt(i);
                       }
                       x="";
                       ++l;
                       break;
                   }
            }
        }
        System.out.println(arr1);
    }
}

错误:

error: variable n might not have been initialized
        for(int i=0;i<n;i++){

这是什么? 变量 n 已经初始化。 我该如何解决?

您只能将char替换为char或将CharSequence替换为CharSequence (因为这些是为String#replace定义的唯一重载),而不能将char替换为String 使用String.valueOf将第一个参数转换为String (即CharSequence )将解决该问题。

ar[j] = ar[j].replace(String.valueOf(ar[i].charAt(k)), "");

如果允许使用 Java 8 stream API,方法simplify如下:

  • 使用 Stream reduce操作来连接输入数组中的字符串
  • 使用带有正则表达式的 String replaceAll方法将所有先前检测到的字符替换为空文字:
public static String simplify(String... arr) {
        
    return Arrays
            .stream(arr)
            .reduce("", // empty accumulator
                (s1, s2) -> s1 + (s1.isEmpty() ? s2 : s2.replaceAll("[" + s1 + "]", ""))
            );
} 

测试:

System.out.println(simplify("abcdef", "fghij"));
System.out.println(simplify("abcdef", "fghij", " jklmn"));

Output

在线演示

abcdefghij
abcdefghij klmn

暂无
暂无

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

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