While循环不在Java中重复

时间:2019-04-13 06:34:59

标签: java

一个程序,用于接收票务订单并提供总数。这不是让我回答我是否想购买更多票的问题。我是一个初学者,如果你们可以指导我或建议任何有帮助的升级。

package ridecalc;
import java.util.Scanner;
/**  *
   1. @author   */
public class Ridecalc {

 /**
  * @param args the command line arguments
  */
 public static void main(String[] args) {
  // TODO code application logic here
  Scanner in = new Scanner(System.in);
  double tickets = 0;
  double totprice;
  String moretickets = "";
  System.out.println("Hi! welcome to JP's amusment park");
  do {
   if (response()) {
    System.out.println("How many tickets would you like to purchase ?");
    tickets = in.nextInt();
   } else {
    totprice = 0;
   }
   totprice = calc(tickets);
   System.out.println("The total amount for the tickets are :" + totprice);
   System.out.println("Would you like to buy more tickets ?(y/n)");
   moretickets = in.nextLine();
  } while (moretickets.equalsIgnoreCase("y"));
 }

 public static boolean response() {
  Scanner in = new Scanner(System.in);
  String response = "";
  System.out.println("Would you like to buy any tickets (y/n)");
  response = in.nextLine();
  if (response.equalsIgnoreCase("y")) {
   return true;
  } else {
   return false;
  }
 }

 public static double calc(double tickets) {
  double totprice;
  totprice = (tickets * 20);
  return totprice;
 }
}

列表项

1 个答案:

答案 0 :(得分:0)

首先,您的response.equalsIgnoreCase("y")永远都不会为真,因为它始终是一个空字符串,对变量response没有任何影响。因此,我添加了一个boolean rps,它将存储用户对您的函数response()的响应,并循环直到它为真为止。

编辑:固定使用了扫描仪,仅一个扫描仪实例 编辑2:修正了双重条件

package ridecalc;
import java.util.Scanner;
/**  *
   1. @author   */
public class some {

 /**
  * @param args the command line arguments
  */
 public static void main(String[] args) {
  // TODO code application logic here
  Scanner in = new Scanner(System.in);
  double tickets = 0;
  double totprice;
  String moretickets = "";
  System.out.println("Hi! welcome to JP's amusment park");

  boolean rps = true;
  while( rps ){
   if ( (rps = response(in)) == true) {
    System.out.println("How many tickets would you like to purchase ?");
    tickets = in .nextInt();
   } else {
    totprice = 0;
   }
   totprice = calc(tickets);
   System.out.println("The total amount for the tickets are :" + totprice);
   System.out.println("Would you like to buy more tickets ?(y/n)");     // this doesn't seem necessary since there is no test following
   in.next();
   moretickets = in.nextLine();
  }
 }

 public static boolean response(Scanner in) {
  String response = "";
  System.out.println("Would you like to buy any tickets (y/n)");
  response = in.nextLine();
  if (response.equalsIgnoreCase("y")) {
    System.err.println("here");
   return true;
  } else {
   return false;
  }
 }

 public static double calc(double tickets) {
  double totprice;
  totprice = (tickets * 20);
  return totprice;
 }
}