我正在用 Java 制作一个计算机定价程序。我试图找出一种方法来生成由用户输出确定的子类。到目前为止,这是我的代码。我意识到我多次运行相同的方法,但我不知道任何其他方法来获取变量以测试输出。For some reason when the b.getScreenPrice(screenPrice)
isn't executed when 2 is picked. 如果有帮助,任何答案。谢谢
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Computer {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(in);
public Computer() {
}
public String pickComputer() {
String comp = null;
System.out.println("Select a number for desired computer:");
System.out.println("1. Desktop");
System.out.println("2. Laptop");
try {
comp = keyboard.readLine();
if (comp.equals("1")) {
comp = "Desktop";
}
if (comp.equals("2")) {
comp = "Laptop";
}
} catch (IOException e) {
pickComputer();
}
return comp;
}
public class Notebook extends Computer {
public String getScreenSize() {
String size = null;
System.out.println("Select a number for the desired screen size:");
System.out.println("1. 19 inch ($200)");
System.out.println("2. 17 inch ($150)");
System.out.println("3. 15 inch ($100)");
try {
size = keyboard.readLine();
if (size.equals("1")) {
size = "19";
}
if (size.equals("2")) {
size = "17";
}
if (size.equals("3")) {
size = "15";
}
} catch (IOException e) {
getScreenSize();
}
return size;
}
public int getScreenPrice(String screen) {
int sPrice = 0;
if (screen.equals("19")) {
sPrice = 200;
}
if (screen.equals("17")) {
sPrice = 150;
}
if (screen.equals("15")) {
sPrice = 100;
}
return sPrice;
}
public void calculatePrice(int screeen) {
System.out.println(screeen);
}
}
public class ComputerTester {
public static void main(String[] args) {
Computer a = new Computer();
Notebook b = new Notebook();
String screenSize = b.getScreenSize();
String newComputer = a.pickComputer();
if (newComputer.equals("Desktop")) {
System.out.println("Test Worked");
}
if (newComputer.equals("Laptop")) {
b.getScreenPrice(screenSize);
}
}
}
}
输出:
Select a number for the desired screen size:
1. 19 inch ($200)
2. 17 inch ($150)
3. 15 inch ($100)
1
Select a number for desired computer:
1. Desktop
2. Laptop
2