如何使这个java程序打印?

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

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

  1. package myproject;
  2. public class broke {
  3. public static void main(String[] args){
  4. boolean success = false;
  5. String integer = "";
  6. if(integer.indexOf("2") == 3){
  7. success = true;
  8. }
  9. if(success){
  10. System.out.println(integer);
  11. }
  12. }
  13. }
rqdpfwrv

rqdpfwrv1#

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

  1. public class Main {
  2. public static void main(String[] args) {
  3. boolean success = false;
  4. String integer = "543210";
  5. if (integer.indexOf("2") == 3) {
  6. success = true;
  7. }
  8. if (success) {
  9. System.out.println(integer);
  10. }
  11. }
  12. }

输出:

  1. 543210

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

展开查看全部
hrirmatl

hrirmatl2#

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

uajslkp6

uajslkp63#

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

  1. System.out.println(integer);

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

相关问题