java - 打印不带任何0的字符串

标签 java error-handling

因此,我有一个项目,他们告诉我必须接收一个正整数,并将其更改为字符串带,我必须用didgit对其进行处理。

private static String intToString(int n) {
    if (n < 0)
        throw new IllegalArgumentException("o nº recebido tem de ser 
positivo: " + n);

    // else if((x != (int)x)){
    // throw new IllegalArgumentException("")
    // }

    else {
        String text = "";
        int array[] = new int[(int) (Math.log10(n) + 1)];
        for (int x = 0; x < array.length; x++) {
            array[x] = n % 10;
            n = n / 10;
        }
        for (int x = array.length - 1; x >= 0; x--) {
            text = text + String.valueOf(array[x]);

        }
        System.out.println(text);
    }
    return null;
}

完成之后,下一部分将删除该字符串上的所有0,然后执行以下操作:
private static int removeZeros(int n) {
    String text = intToString(n);
    for (int l = 0; l < text.length(); l++) {
        if (text[l] != "0") {
            System.out.println("Sick");;
        }
    }
    return 0;
}

但这给了我这个错误:
表达式的类型必须是数组类型,但是它解析为String。

我该怎么解决这个错误?

最佳答案

字符串不是数组,尽管它当然是通过底层的数组实现的。

对于一个字符串,你可以做

text.charAt(l)

代替
text[l]

然后与“0”(字符)而不是“0”(字符串)进行比较。

关于java - 打印不带任何0的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43552966/

相关文章:

Java - 图像着色

android - iOS中的Kotlin Multiplatform Mobile : How to handle errors (network, db等)?

php - 重新连接 MySQL 服务器已经消失

java - 从 1-300 生成 30 个随机数的数组返回全 0 而不是其他数字

Java FTPClient 不传输整个文件

java - 使用 Selenium Webdriver 的 IE 浏览器 : "The driver executable is a directory"

error-handling - 如何显示从 Javascript SDK 返回的错误

ruby - 抢救,调用抢救方法

python - 如何在Django和Django Rest框架中覆盖/自定义所有服务器错误

java - Eclipse Java 编辑器突出显示错误但代码可以编译