如何让这个java程序打印出来?
How to make this java program to print?
我不知道该怎么做,但我不能打印任何东西。我是编程初学者,现在有点迷路。
所以问题是我需要在 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);
}
}
}
您正在创建一个名为“integer”的字符串变量,并将其值设置为“”(空字符串)。
System.out.println(integer);
上面的代码片段,如果不是奇怪的 if 语句..会打印你的字符串..但是你的字符串是空的,所以打印只会包含一个 \n 被发送到 System.out.
没有打印的原因是方法调用“string.indexOf("2")" returns -1(表示未找到字符“2”)。
我在您的评论中看到,您尝试使用字符串“3333”进行此操作,但不出所料,还是找不到字符“2”。
我 运行 你的代码设置了 String integer = "2",它工作正常。
也许您对属于 String class 的 indexOf() 方法的工作原理感到困惑。它 returns 作为参数传入的值出现的第一个索引。
您的程序只会在 success
为 true
时打印,因为语句 if(integer.indexOf("2") == 3)
为 false
(整数为空),success
将为false
,因此System.out.println(integer);
不会被执行。
任何在索引处有 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
中,5
的索引是0
,从这个索引开始,2
的索引是3
。
我不知道该怎么做,但我不能打印任何东西。我是编程初学者,现在有点迷路。
所以问题是我需要在 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);
}
}
}
您正在创建一个名为“integer”的字符串变量,并将其值设置为“”(空字符串)。
System.out.println(integer);
上面的代码片段,如果不是奇怪的 if 语句..会打印你的字符串..但是你的字符串是空的,所以打印只会包含一个 \n 被发送到 System.out.
没有打印的原因是方法调用“string.indexOf("2")" returns -1(表示未找到字符“2”)。
我在您的评论中看到,您尝试使用字符串“3333”进行此操作,但不出所料,还是找不到字符“2”。
我 运行 你的代码设置了 String integer = "2",它工作正常。
也许您对属于 String class 的 indexOf() 方法的工作原理感到困惑。它 returns 作为参数传入的值出现的第一个索引。
您的程序只会在 success
为 true
时打印,因为语句 if(integer.indexOf("2") == 3)
为 false
(整数为空),success
将为false
,因此System.out.println(integer);
不会被执行。
任何在索引处有 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
中,5
的索引是0
,从这个索引开始,2
的索引是3
。