我试图让骰子滚动,我在某处添加循环时遇到了一些困难,所以程序在一次滚动后就不会退出。我想询问用户是否要滚动,然后通过说" y来滚动。"我想通过询问用户相同的问题结束该程序,但它以" n"
结束/*
Natasha Shorrock
Assignmnt A6
11/07/16
*/
package diceroller;
import java.util.Random;
import java.util.Scanner;
public class DiceRoller {
public static void main(String []args) {
System.out.println(" Do you want to roll the dice? ");
Random dice = new Random();
Scanner input = new Scanner(System.in);
int faces;
int result;
System.out.println("Dice Roller\n");
System.out.println("How many faces does the dice have?");
faces = input.nextInt();
result = dice.nextInt(faces) + 1;
System.out.println("\nThe dice rolled a " + result );
}//Dice Roller
}//class DiceRoller
答案 0 :(得分:0)
您必须在以下表达式后阅读输入:
System.out.println(" Do you want to roll the dice? ");
接收用户输入电话:input.nextLine();
。此后循环,输入为"y"
。如果用户输入不等于"y"
,while-loop
将被终止。
只要条件为while(condition)
true
循环就会被执行
当特定条件为真时,while语句会不断执行一个语句块。 The while and do-while Statements
例如,请考虑以下代码:
public static void main(String[] args) {
Random dice = new Random();
Scanner input = new Scanner(System.in);
System.out.println("Do you want to roll the dice? (y: yes / q: to quit)");
String answer = input.nextLine(); // reading the input
// we check if the answer is equals to "y" to execute the loop,
// if the answer is not equals to "y" the loop is not executed
while ("y".equals(answer)) {
System.out.println("Dice Roller");
System.out.println("How many faces does the dice have?");
int faces = input.nextInt();
int result = dice.nextInt(faces) + 1;
input.nextLine(); // to read the newline character (*)
System.out.println("The dice rolled a " + result);
System.out.println("Do you want to roll the dice? (y: yes / q: to quit)");
answer = input.nextLine();
}
}
要了解有关while和Do-while机制的更多信息,请访问此toturial
(*)要了解在调用nextInt()之后使用nextLine(),请访问Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
答案 1 :(得分:0)
锻炼是一个非常好的选择。另一种方法是使用带开关的while循环或最好使用IF / ELSE IF语句。也许就像下面这样。这只是一个建议。
boolean checkForExit = false;
while(checkForExit != true) { //while checkForExit does not equal true (therefore false) continue..
System.out.println("Do you want to roll the dice?");
String answer = input.next(); //get char input from user.
if(answer.toLowerCase().equals("y")) { //if 'y' then do this
//ask user for number of faces on dice and roll
} else { // otherwise end the program
//set isTrue to true to exit while loop. ends program
isTrue = true;
}
}