gpt4 book ai didi

java - 在第一个循环后执行 while 循环不正确打印

转载 作者:行者123 更新时间:2023-11-29 08:50:55 24 4
gpt4 key购买 nike

我正在尝试执行一个 do-while 循环,使程序在用户输入“y”或“Y”后再次迭代,但每次我运行该程序时,它都会打印出如下内容:

Would you like to try again?Enter Y for yes or N for no:  [DrJava Input Box] (I enter y)Are you a student? (no input box is shown, and it skips it)Are you a member of staff or faculty? [DrJava Input Box] (i enter yes or no)How many tickets do you need? [DrJava Input Box] (I enter an int, but it doesnt complete that part where it shows how many tickets sold or how much it costs)Would you like to try again? Enter Y for yes or N for no: [DrJava Input Box]

this is what my program looks like:

import java.util.Scanner;

public class Ticket
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);

double ticketprice = 12.00;
double result;
double result2;
double result3;
char repeat;
String input;
String student;
String staff;
int ticket;

do
{
System.out.println("Are you a student?");
student = keyboard.nextLine();


System.out.println("Are you a member of staff or faculty?");
staff = keyboard.nextLine();


System.out.println("How many tickets do you need?");
ticket = keyboard.nextInt();



if(student.equals("yes"))
{
System.out.println("Here is your " + ticket + " tickets for $0.00");
}


if(staff.equals("yes"))
{
result = ticketprice * .85;
result2 = ticket * result;
System.out.printf("Here are your " + ticket + " tickets for $%.2f\n", result2);
}



if(student.equals("no") && staff.equals("no"))
{
result3 = ticket * ticketprice;
System.out.printf("Here are your " + ticket + " tickets, for $%.2f\n", result3);
}


System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);

}
while(repeat == 'y' || repeat == 'Y');

}
}

我是编程初学者,所以任何帮助都会很好。谢谢。

最佳答案

在循环结束时,您调用 next() 来读取“重试”响应。这会读取下一个标记,但仍会留下以输入流结尾的行。

下一次通过循环,当您调用 nextLine() 来读取“您是学生吗”响应时,它会立即读取该行的剩余部分。

最简单的解决方案是:

  • 使用 nextLine() 而不是 next() 来提示“再试一次”,但这意味着您必须处理左边结尾的行通过 nextInt() 在“门票”问题中,那么您必须...
  • 使用 nextLine() 而不是 nextInt() 来解决“门票”问题,然后使用 Integer.parseInt() 解析字符串转换成一个整数。

由于您的所有响应似乎都只是单个单词响应,因此另一种选择是在任何地方都使用 next()/nextInt() 而不是使用 nextLine() 完全没有。关键是,当您将两者混合使用时,您必须了解它们如何相互作用。

关于java - 在第一个循环后执行 while 循环不正确打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751398/

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