尝试在Java中将if语句值添加到总答案中
Java非常陌生,因此试图理解它可能很困难 不管怎么说,作为任务的一部分,我必须编写一个剧院门票控制台应用程序。我几乎完成了我只是想添加最后一部分 作为任务的一部分,我们必须询问用户是否希望张贴车票,如果是,将产生一笔费用,该费用将应用于总费用。目前,我不确定如何做到这一点。目前,我正在处理If和else语句以及。。你会看到下面尝试在Java中将if语句值添加到总答案中,java,if-statement,Java,If Statement,Java非常陌生,因此试图理解它可能很困难 不管怎么说,作为任务的一部分,我必须编写一个剧院门票控制台应用程序。我几乎完成了我只是想添加最后一部分 作为任务的一部分,我们必须询问用户是否希望张贴车票,如果是,将产生一笔费用,该费用将应用于总费用。目前,我不确定如何做到这一点。目前,我正在处理If和else语句以及。。你会看到下面 System.out.println ("Do you require the tickets to be posted?\n(£2.34 for post an
System.out.println ("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");
String postinp = scanner.next();
if ("Yes".equals(postinp)){
System.out.println("Postage will be added to your cost" );
}
else
System.out.println("Postage will not be added to your cost");
我正在尝试编码,如果用户输入“是”,那么它会将邮费加到总数中,但在这段代码中,我不确定如何做到这一点
任何帮助都将不胜感激。谢谢 使用scanner.nextLine()插入scanner.next()
用“是”代替“是”我要做的就是改变
if ("Ye".equals(postinp)) {
到
这样,它就不会对用户输入的内容区分大小写,因为否则他们就必须准确地输入
Yes
。您可以在中添加更多的代码,然后在if
语句的else
块中添加代码
if ( "Yes".equals(postinp) )
{
this.cost += 2.34 ; // or whatever it is you need to do
System.out.println("Postage will be added to your cost" );
}
else
{
System.out.println("Postage will not be added to your cost");
}
在
if语句中
我们需要做的就是将您的2.34英镑添加到程序计算的总金额中
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double total = 10.00;
System.out.println("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");
if ("Yes".equalsIgnoreCase(input.next())) {
System.out.println("Postage will be added to your cost");
total = total + 2.34;
} else
System.out.println("Postage will not be added to your cost");
}
你似乎需要解决两件事——评估答案,然后据此采取行动 试试这个:
String postinp = scanner.next();
if ("Yes".equalsIgnoreCase(postinp)) {
cost += postage;
System.out.println("Postage will be added to your cost" );
}
else {
System.out.println("Postage will not be added to your cost");
}
if
块检查结果是否为某种形式的“yes”,而不考虑大小写。然后它假设cost
和postage
变量(float
s)是可用的,并从某处初始化。在“是”的情况下,成本
由邮资
增加
此外,因为你只是学习它不是什么大不了的事,但在某些时候,你可能想考虑你的邮资是一个价值从一个常数或从配置文件消费。也许初始成本也可以。
如果我们只期望一个字,那也没关系。你能告诉我在哪里初始化扫描仪吗?你需要为费用设置一个变量,并将其相加。你是把费用作为一个数字,还是只处理字符串?没关系,除了“Ye”之外。。它应该是“是”您到底有什么问题?或者您可以直接使用.equalsIgnoreCase
那么您的总成本是多少?您没有向我们提供上面的代码。在我的回答中,只需将您的总成本替换为total
。很抱歉,只需更改代码,就可以了。我可以问一下为什么双人在这里不起作用吗?@TomCummins双人在这里起作用,因为你已经提供了2.34加到我们的总数中,我们不能使用int
。float
也适用。我的猜测是,您需要更改包含总数的变量的类型。好的,谢谢您的帮助,我在过去一个小时内一直在尝试解决这个问题。我用的是:double post0=total+2.34;但那不起作用。
String postinp = scanner.next();
if ("Yes".equalsIgnoreCase(postinp)) {
cost += postage;
System.out.println("Postage will be added to your cost" );
}
else {
System.out.println("Postage will not be added to your cost");
}