gpt4 book ai didi

java - 如何在Java中使用if有条件地循环语句?

转载 作者:行者123 更新时间:2023-12-01 13:21:41 27 4
gpt4 key购买 nike

我刚刚开始在类里面学习 Java。作业是制作一个石头剪刀布游戏,这是我的源代码。我已经上交了,但还没有收到成绩。

package rockpaperscissors;

import java.util.Random;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
// Create scanner input
Scanner input = new Scanner (System.in);

// Introduce user to game
System.out.println("Welcome to the Rock, Paper and Scissors game");

// Ask the user for their move
System.out.println("\nPlease select a move\nEnter 0 for Scissors, 1 "
+ "for Rock and 2 for Paper");
int userMove = input.nextInt();

// Ensure that userMove is between 0 and 2
if (userMove > 2 || userMove < 0) {
System.out.println("Invalid entry the result of this game will not "
+ "be accurate! Please retry using either 0 for Scissors, 1"
+ " for Rock and 2 for Paper\n");
}

// Generate computerMove using java.util.Random
// Create instance first
Random MyRandom = new Random();

//Now generate number
int computerMove = MyRandom.nextInt(3);

System.out.print("The computer played " + computerMove + "\nRemember"
+ " 0 stands for Scissors, 1 is for Rock and 2 is for paper\n");

// Determine draw result
if (userMove == computerMove) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The game is a draw!");
}
// Determine computer win
else if(userMove == 0 && computerMove == 1) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The Computer Wins!");


}

else if(userMove == 2 && computerMove == 0) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The Computer Wins!");

}

else if(userMove == 1 && computerMove == 2) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The Computer Wins!");

}

/* Determine User win, as no other moves can result in computer win all
other combinations will result in user win
*/

else {
System.out.print("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " You Win!");
}



}

}

如果数字大于 2 或小于 0,我无法让程序重新请求数字,它会显示“无效输入,结果将无效...”,但它仍会执行程序的其余部分具有无效编号。

如何让程序停止并提示用户输入有效号码,然后执行程序?此外,这是我制作的第三个程序,因此任何其他建议将不胜感激。

谢谢

最佳答案

如果满足您的条件,您想要的是不执行所有其他代码。

现在,当满足您的条件时,您会给出错误消息 - 但不会停止函数其余部分的执行。

你可以停下来。

那么 - 在不告诉你确切答案的情况下...如何退出函数?在显示错误消息后立即执行此操作,就可以了。

但是 - 如果您想继续获取用户输入直到满足条件...这需要围绕获取和检查的部分进行循环。

你知道什么循环?

你知道有一个可以让你循环直到满足某些条件吗?

你已经有了你的条件...现在你只需要调整一个循环来让你重复执行你想要的代码,直到满足该条件。

伪代码(即这不是真正的java - 你必须翻译):

some_loop do
fetch user input
give error message if its not ok
until (user input is ok)

关于java - 如何在Java中使用if有条件地循环语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21977160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com