私の課題:
ユーザーがフィートに正の整数、インチに負でない 10 進数、重量に正の 10 進数を入力することを確認して、入力の検証を実行します。詳しくはサンプルセッションをご覧ください。特に、エコー印刷された身長と体重の値、および生成されたボディマスインデックス値の形式に注意してください。
私のプログラムは動作しますが、以下のサンプル プログラムのようにする方法がわかりません。ユーザーに高さをフィート、次にスペース、インチで入力させる必要があります。ユーザー入力をスペースで分割する方法がわかりません。
サンプル セッション:
Enter height using feet space inches (e.g., 5 6.25): hi there
Invalid feet value. Must be an integer.
Invalid inches value. Must be a decimal number.
Re-enter height using feet space inches (e.g., 5 6.25): 0 9
Invalid feet value. Must be positive.
Re-enter height using feet space inches (e.g., 5 6.25): 5.25 0
Invalid feet value. Must be an integer.
Re-enter height using feet space inches (e.g., 5 6.25): 5 9.25
Enter weight in pounds: 0
Invalid pounds value. Must be positive.
Re-enter weight in pounds: 150.5
height = 5'-9.25"
weight = 150.5 pounds
body mass index = 22.1
これまでの私のコード:
package ch14;
import java.util.Scanner;
public class BMI {
public static void main(String[] args) {
String inputString;
double bmi;
double pounds;
double inches;
String feet;
Scanner stdIn = new Scanner(System.in);
System.out.print("Please enter height using feet space inches (e.g., 5 6.25): ");
inputString = stdIn.nextLine();
try
{
Double.parseDouble(inputString);
}
catch(NumberFormatException nfe)
{
System.out.println ("Invalid inch value. Number must be a decimal.");
System.out.print ("Re-enter height in inches: ");
inputString = stdIn.nextLine ();
}
inches=Double.parseDouble(inputString);
if(inches<=0)
{
System.out.println("Invalid inch value. Must be a positive number.");
System.out.print("Re-enter height in inches:");
inputString = stdIn.nextLine();
inches=Double.parseDouble(inputString);
}
System.out.print("enter weight(in pounds) ");
inputString = stdIn.nextLine();
try
{
Double.parseDouble(inputString);
}
catch(NumberFormatException nfe)
{
System.out.println("Invalid pound value. Number must be a decimal.");
System.out.print("Re-enter the weight in pounds: ");
inputString = stdIn.nextLine();
}
pounds=Double.parseDouble(inputString);
if(pounds <= 0)
{
System.out.println("Invalid pound value. Must be a positive number.");
System.out.print("Re-enter the weight in pounds:");
inputString = stdIn.nextLine();
pounds=Double.parseDouble(inputString);
}
System.out.println("Height = " + inches + "\"");
System.out.println("Weight = " + pounds + " pounds");
System.out.printf("Body Mass Index = %.1f\n",(pounds * 703.)/(inches * inches));
}//end main
}