我目前有以下代码写道:
import java.util.Scanner;
public class TicketPriceWithDiscount {
public static void main(String[] args) {
TicketPriceWithDiscount obj = new TicketPriceWithDiscount();
}
public TicketPriceWithDiscount(){
double regPrice = 9.25;
double otherPrice = 5.25; // ages under 12 or over 65
double discount = 2.00;
String person;
int pInput;
Scanner keyboard = new Scanner(System.in);
System.out.println("What is your age?");
pInput = keyboard.nextInt();
System.out.println("Do you have a coupon? Yes or no will do.");
person = keyboard.nextLine();
if(person == "yes" && pInput <= 12 || pInput >= 65){
otherPrice = otherPrice - discount;
System.out.println("Your ticket price is: " + otherPrice);
}
else if(person == "yes" && pInput >= 12 && pInput <= 65){
regPrice = regPrice - discount;
System.out.println("Your ticket price is: " + regPrice);
}
else if(pInput <= 12 || pInput >= 65){
System.out.println("Your ticket price is: " + otherPrice);
}
else if(pInput >= 12 || pInput <= 65) {
System.out.println("Your ticket price is: " + regPrice);
}
}
}
该程序运行到我要求该人输入或不输入优惠券的程度。
System.out.println("Do you have a coupon? Yes or no will do.");
person = keyboard.nextLine();
此时,程序不会等待输入并根据年龄输入完成if语句,它会等待用户的回复。
用于输入年龄的输出,对优惠券问题说是或否,以及程序根据这些答案继续运行。
我尝试过:
非常感谢指导。
答案 0 :(得分:1)
我认为您的nextLine会在您的
之后读取新的换行符keyboard.nextInt();
尝试添加
keyboard.nextLine();
之后
keyboard.nextInt();
重置扫描仪。
答案 1 :(得分:0)
您似乎遇到与this question with solution相同的问题。当然是奇怪的怪癖!
答案 2 :(得分:0)
更改为:
import java.util.Scanner;
public class TicketPriceWithDiscount {
public static void main(String[] args) {
TicketPriceWithDiscount obj = new TicketPriceWithDiscount();
}
public TicketPriceWithDiscount(){
double regPrice = 9.25;
double otherPrice = 5.25; // ages under 12 or over 65
double discount = 2.00;
String person;
int pInput;
Scanner keyboard = new Scanner(System.in);
System.out.println("What is your age?");
pInput = keyboard.nextInt();
System.out.println("Do you have a coupon? Yes or no will do.");
//change to next() not nextLine()
//because nextLine is used when you read a file
person = keyboard.next();
//use equals not == and don't forget the parentheses
if(person.equals("yes") && (pInput <= 12 || pInput >= 65)){
otherPrice = otherPrice - discount;
System.out.println("rani hna");
System.out.println("Your ticket price is: " + otherPrice);
}
//use equal not ==
else if(person.equals("yes") && pInput >= 12 && pInput <= 65){
regPrice = regPrice - discount;
System.out.println("Your ticket price is: " + regPrice);
}
else if(pInput <= 12 || pInput >= 65){
System.out.println("Your ticket price is: " + otherPrice);
}
else if(pInput >= 12 || pInput <= 65) {
System.out.println("Your ticket price is: " + regPrice);
}
}
}