如何使这个java程序打印?

6ie5vjzr  于 2021-07-11  发布在  Java
关注(0)|答案(3)|浏览(245)

我不知道该怎么办,但我不能用这个打印任何东西。我是编程初学者,现在有点迷路了。所以问题是我需要在 String integer = ""; 把这张照片印出来?我在用java。谢谢你的帮助。

package myproject;

public class broke {

    public static void main(String[] args){

        boolean success = false;
         String integer = "";
            if(integer.indexOf("2") == 3){
                success = true;
            }
             if(success){
                System.out.println(integer);
             }
    }
}
rqdpfwrv

rqdpfwrv1#

任何有 2 在索引处, 3 会创造条件, integer.indexOf("2") == 3 是的。请注意,索引从 0 一串串。
演示:

public class Main {
    public static void main(String[] args) {
        boolean success = false;
        String integer = "543210";
        if (integer.indexOf("2") == 3) {
            success = true;
        }
        if (success) {
            System.out.println(integer);
        }
    }
}

输出:

543210

在弦中, 543210 ,的索引 50 从这个索引开始 23 .

hrirmatl

hrirmatl2#

你的程序只会在 successtrue ,自从声明之后, if(integer.indexOf("2") == 3)false (整数为空), successfalse ,因此 System.out.println(integer); 不会被执行。

uajslkp6

uajslkp63#

您正在创建一个名为“integer”的字符串变量,并将其值设置为“”(空字符串)。

System.out.println(integer);

上面的片段,如果不是奇怪的if语句。。会打印你的字符串。。但是您的字符串是空的,因此打印将只包括发送到system.out的\n。
nothing正在打印的原因是,方法调用“string.indexof(“2”)”返回-1(表示未找到字符“2”)。
我在你的评论中看到,你用字符串“3333”尝试了这个方法,而且,很有可能,字符“2”也找不到。
我用设置字符串integer=“2”运行了您的代码,效果很好。
可能您的困惑是属于string类的indexof()方法是如何工作的。它返回作为参数传入的值所在的第一个索引。

相关问题