为什么这个程序不会执行 if else 语句中的内容
package com.company;import java.util.Scanner;
import java.util.Random;
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("程序已启动");
System.out.println("剪刀\t石头\t布");
int a=0;
for(int i=1;i<=5;i++)
{
System.out.println("第"+i+"局");
Scanner scanner1=new Scanner(System.in);
String s = scanner1.nextLine();
int randomNumber=new Random().nextInt(3);
//1 代表石头 2 代表剪刀 3 代表布
switch (randomNumber+1) {
case(1)://石头
{
System.out.println("电脑本次出的是石头");
if (s == "石头") {
System.out.println("打平了");
}
else if (s == "剪刀") {
System.out.println("赢了");
a++;
} else if (s == "布") {
System.out.println("输了");
a--;
}
break;
}
case(2)://剪刀
{
System.out.println("电脑本次出的是剪刀");
if (s=="石头") {
System.out.println("输了");
a--;
}
else if (s=="剪刀"){
System.out.println("打平了");
}
else if(s=="布"){
System.out.println("赢了");
a++;
}
break;
}
case(3)://布
{
System.out.println("电脑本次出的是布");
if (s=="石头")
{
System.out.println("赢了");
a++;
}
else if (s=="剪刀"){
System.out.println("输了");
a--;}
else if(s=="布"){
System.out.println("打平了");
}
break;
}
}
}
if(a>0)
System.out.println("本次游戏胜利");
else if(a==0)
System.out.println("本次游戏平局");
else if(a<0)
System.out.println("本次游戏失败");
// write your code here
}
}
运行结果:
程序已启动
剪刀 石头 布
第1局
石头
电脑本次出的是石头
第2局
石头
电脑本次出的是布
第3局
石头
电脑本次出的是石头
第4局
石头
电脑本次出的是布
第5局
石头
电脑本次出的是剪刀
本次游戏平局
进程已结束,退出代码为 0
将你代码中字符串判断都改成 equals() 了,你再测试看看:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
System.out.println("程序已启动");
System.out.println("剪刀\t石头\t布");
int a = 0;
for (int i = 1; i <= 5; i++) {
System.out.println("第" + i + "局");
Scanner scanner1 = new Scanner(System.in);
String s = scanner1.nextLine();
int randomNumber = new Random().nextInt(3);
//1 代表石头 2 代表剪刀 3 代表布
switch (randomNumber + 1) {
case (1)://石头
{
System.out.println("电脑本次出的是石头");
if ("石头".equals(s)) {
System.out.println("打平了");
} else if ("剪刀".equals(s)) {
System.out.println("赢了");
a++;
} else if ("布".equals(s)) {
System.out.println("输了");
a--;
}
break;
}
case (2)://剪刀
{
System.out.println("电脑本次出的是剪刀");
if ("石头".equals(s)) {
System.out.println("输了");
a--;
} else if ("剪刀".equals(s)) {
System.out.println("打平了");
} else if ("布".equals(s)) {
System.out.println("赢了");
a++;
}
break;
}
case (3)://布
{
System.out.println("电脑本次出的是布");
if ("石头".equals(s)) {
System.out.println("赢了");
a++;
} else if ("剪刀".equals(s)) {
System.out.println("输了");
a--;
} else if ("布".equals(s)) {
System.out.println("打平了");
}
break;
}
}
}
if (a > 0)
System.out.println("本次游戏胜利");
else if (a == 0)
System.out.println("本次游戏平局");
else System.out.println("本次游戏失败");
// write your code here
}
}
字符串不能使用 == 直接进行判断
== 判断的是地址值是否相等,判断字符串是否相等应该使用 equals()
而且建议将已知字符串写为 equals 的调用对象,例如 "石头".equals(s) ,这样能有效避免空指针异常
Twilight6 发表于 2022-9-6 09:37
将你代码中字符串判断都改成 equals() 了,你再测试看看:
谢谢啦 之前一直不知道怎么办呢
页:
[1]