2 回答

TA貢獻1966條經驗 獲得超4個贊
您應該更改此方法以返回這樣的心率:
public int getHeartRate(){
System.out.print("Please enter your heart rate: ");
Scanner scan = new Scanner(System.in);
int heartRate = scan.nextInt();
// Also add this
scan.close();
return heartRate;
}
并更改此方法以返回結果:
public String checkHeartRate(int heartRate){
if (heartRate > 100) {
return "High";
}
else if (heartRate < 60) {
return "Low";
}
else {
return "Normal";
}
}
然后在你的主要方法中:
// get the heart rate
int heartRate = u.getHeartRate();
// Call the checkHeartRate method
String result = checkHeartRate(heartRate);
// call the printHRResults
printHRResults(result);
那應該可以解決您的問題。

TA貢獻1828條經驗 獲得超13個贊
首先,您要創建兩個Scanner具有相同輸入類型 ( System.in) 的對象,這是不推薦的。相反,只需創建一個Scanner對象并在程序中的任何地方使用它。這篇文章有一些很好的信息。
改進了Scanner對象使用的代碼的改進版本如下:
public UnitSixInClassFall2018 {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
NewMain u = new NewMain();
int heartRate = u.getHeartRate();
System.out.println();
String result = u.checkHeartRate(heartRate);
u.printHRResults(result);
scan.close(); // Close the scanner once you are completely done using it
}
public int getHeartRate() {
System.out.print("Please enter your heart rate: ");
return scan.nextInt(); // Return the input of the user
}
public String checkHeartRate(int heartRate) {
String result = ""; // Initialize some default value
if (heartRate > 100) {
result = "High";
}
else if (heartRate < 60) {
result = "Low";
}
else {
result = "Normal";
}
return result; // Return the result calculated from the if-statements
}
public void printHRResults(String result) {
System.out.print("Your heart rate is " + result + ".");
// Originally this method returned a string but that seems unnecessary
}
}
添加回答
舉報