[英]Need Help working with Nested For loop to display a block of text (Java)
[英]java nested for loop not working…help please
我是Java的新手,我试图用Eclipse编写一个程序,当用户键入'r'时,它将随机选择一把枪“给”他们五把枪之一。使命召唤僵尸。 我对为什么输入“ r”后为什么不输出随机“ gun”感到困惑。 请帮忙!!!
import java.util.Random;
import java.util.Scanner;
class apples{
public static void main(String[] args){
System.out.println("Type 'r' for a random gun");
Random dice = new Random();
int number;
Scanner input = new Scanner(System.in);
String userinput = input.nextLine();
if (userinput=="r"){
for (int counter=1; counter<=1; counter++){
number = 1+dice.nextInt(5);
if (number==1){
System.out.println("gun 1");
}else if (number==2){
System.out.println("gun 2");
}else if (number==3){
System.out.println("gun 3");
}else if (number==4){
System.out.println("gun 4");
}else if (number==5){
System.out.println("gun 5");
}
}
}else{
System.out.println(" ");
}
}
}
尝试使用
int randomInt = dice.nextInt(4);
if(userInput.equals("r")){
if (randomInt==1){
System.out.println("gun 1");
}else if (randomInt==2){
System.out.println("gun 2");
}else if (randomInt==3){
System.out.println("gun 3");
}else if (randomInt==4){
System.out.println("gun 4");
}else if (randomInt==5){
System.out.println("gun 5");
}
}
所以总体的最终代码应该像
public class test {
public static void main(String[] args) {
System.out.println("Type 'r' for a random gun");
Random dice = new Random();
int number;
Scanner input = new Scanner(System.in);
String userinput = input.nextLine();
int randomInt = dice.nextInt(4);
if (userinput.equals("r")) {
if (randomInt == 1) {
System.out.println("gun 1");
} else if (randomInt == 2) {
System.out.println("gun 2");
} else if (randomInt == 3) {
System.out.println("gun 3");
} else if (randomInt == 4) {
System.out.println("gun 4");
} else if (randomInt == 5) {
System.out.println("gun 5");
}
}
}
}
编辑-抱歉,呵呵! 我没有注意到@lal的评论,显然他首先注意到了该错误,因此我的回答是他的阐述。
当您这样做时:
if (userinput=="r")
您实际上是在比较对象的引用,而不是实际的对象。operator ==
比较对象的引用,因此输出实际上是“false”
而不是“true.”
自然,这首先使人们感到惊讶。
要纠正此问题,您应该尝试使用equals方法,如下所示:
if (userinput.equals("r"))
请注意, java.lang.Object
的默认equals()
实现比较内存位置,并且仅当两个引用变量指向同一内存位置(即本质上它们是同一对象)时才返回true。因此,要测试两个对象是否相等就等同性( 包含相同的信息 )而言,您必须重写equals()
方法。(不重写equals()
方法,它的作用类似于==
。正如我在对象上使用==
运算符时所说的,它只是检查引用是否属于同一对象,而不是引用的成员包含相同的值。)
但是,这里不需要覆盖,因为String类已经覆盖了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.