嗨,这是我在这里发表的第一篇文章,我有一个问题:
我有一个程序,在某个时候,会询问用户是否想分享星星,如果他愿意,程序就会返回收集星星,一段时间后又回到这个问题,如果他想要的话再次分享。
问题是,当用户返回到该点时,程序会忽略您给出的任何答案并转到“其他答案 block ”。
看起来像这样:
"Do you want to share your stars?
yes
Please answer with yes or no"
代码:
import java.util.Random;
import java.util.Scanner;
public class App {
static Scanner skan = new Scanner(System.in);
static int starCount = 0;
static Random random = new Random();
public static void main(String[] args) {
starReaching();
}
static void starReaching() {
boolean starCollected = false;
int i = 0;
int j = random.nextInt(101);
while (i < j) {
i++;
System.out.println("Stars are out of reach");
}
if (i > j || i == j) {
starCollected = true;
}
if (starCollected == true) {
starCollector();
}
}
static void starCollector() {
System.out.println("You caught a star !");
starCount++;
if (starCount == 10) {
System.out.println("You have 10 stars ! :)");
System.out.println("Do you want to share your stars?");
String line = skan.nextLine();
if (line.equals("yes")) {
skan.reset();
starGiver();
} else if (line.equals("no")) {
wishMaker();
} else {
System.out.println("Please answer with yes or no");
System.exit(0);
}
} else {
starReaching();
}
}
static void starGiver() {
System.out.println("How many do you want to share?");
int starsToShare = skan.nextInt();
if (starsToShare < 10 || starsToShare == 10 && starsToShare > 0) {
starCount = starCount - starsToShare;
System.out.println("Stars shared !");
System.out.println("You now have " + starCount + " stars");
System.out.println("Go collect them again!");
starReaching();
} else if (starsToShare > 10) {
System.out.println("You don't have enough stars to share that much!");
starGiver();
} else {
System.out.println("That's not a valid option");
starGiver();
}
}
static void wishMaker() {
}
}
最佳答案
每次调用skan.nextLine()
时,您都会读取一个新行并推进扫描仪的指针,这就是您的代码失败的原因:您调用此操作的次数太多了。
而不是
if (skan.nextLine().equals("yes")) {
skan.reset();
starGiver();
} else if (skan.nextLine().equals("no")) {
wishMaker();
} else {
做:
String line = scan.nextLine(); // read from Scanner **once** only
if (line.equals("yes")) {
skan.reset();
starGiver();
} else if (line.equals("no")) {
wishMaker();
} else {
关于Java Scanner 忽略答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32301502/