编辑:我的问题已部分解决。现在我可以输入文本了,但是在我输入“shiphalf”值后什么也看不到。我是否错误地构建了 if else 语句?
我试图让人们输入优惠券代码,但我无法弄清楚如何让控制台知道用户正在输入文本。我觉得错误就在这里:
System.out.println("Enter a Coupon Code: ");
String ship = input.nextLine();
但我不完全确定。下面是完整的源代码:
package pseudoPackage;
import java.util.Scanner;
public class PseudoCode {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int ship1 = 0;
int ship2 = 6;
int ship3 = 2;
String shiphalf = null;
System.out.print("How much will shipping cost you?");
System.out.println();
System.out.print("Enter your textbook cost in dollars without the $: ");
double cost = input.nextDouble();
if ( cost >= 100 ) {
System.out.println("Your shipping costs are $0");
} else if ( cost < 100 && cost > 50 ) {
System.out.println("Your shipping cost is $6");
} else if ( cost < 50 ) {
System.out.println("Your shipping cost is $2");
}
System.out.println("Enter a Coupon Code: ");
String ship = input.nextLine();
if ( ship == shiphalf && cost >= 100 ) {
System.out.println("Your shipping costs are $0");
} else if ( ship == shiphalf && cost < 100 && cost >50 ) {
System.out.println("Your shipping costs are $3 ");
} else if ( ship == shiphalf && cost < 50 ) {
System.out.println("Your shipping costs are $1");
}
}
}
最佳答案
你的代码有两个问题:
1. 使用 input.next()
而不是 input.nextLine()
。
2.将您的 if conditional
更改为 ship.equals("shiphalf")
。请记住,您使用 .equals()
来比较 2 个字符串。
这是你的最终代码:
package pseudoPackage;
import java.util.Scanner;
public class PseudoCode {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int ship1 = 0;
int ship2 = 6;
int ship3 = 2;
String shiphalf = null;
System.out.print("How much will shipping cost you?");
System.out.print("\nEnter your textbook cost in dollars without the $: ");
double cost = input.nextDouble();
if ( cost >= 100 ) {
System.out.println("Your shipping costs are $0");
} else if ( cost < 100 && cost > 50 ) {
System.out.println("Your shipping cost is $6");
} else if ( cost < 50 ) {
System.out.println("Your shipping cost is $2");
}
System.out.println("Enter a Coupon Code: ");
String ship = input.next();
if ( ship.equals("shiphalf") && cost >= 100 ) {
System.out.println("Your shipping costs are $0");
} else if ( ship.equals("shiphalf") && cost < 100 && cost >50 ) {
System.out.println("Your shipping costs are $3 ");
} else if ( ship.equals("shiphalf") && cost < 50 ) {
System.out.println("Your shipping costs are $1");
}
}
}
关于java - 为什么我的 java 程序不接受用户的字母输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30551836/