gpt4 book ai didi

java - 从 Java 子类获取值

转载 作者:行者123 更新时间:2023-12-01 04:18:59 24 4
gpt4 key购买 nike

我正在用 Java 制作一个计算机定价程序。我试图找出一种方法来生成由用户输出确定的子类。到目前为止,这是我的代码。我意识到我多次运行相同的方法,但我不知道有任何其他方法来获取变量以测试输出。由于某种原因,当选择 2 时,b.getScreenPrice(screenPrice) 未执行。如果有帮助的话任何答案。谢谢

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

最佳答案

尝试更改您的代码以使用

size = keyboard.readLine().trim();

这将修剪所有尾随和前导空格。如果你打印出你的尺寸,我敢打赌它会在它的末尾有一个换行符,因为按 Enter 键。

关于java - 从 Java 子类获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19166444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com