基本上,不是从用户那里读取一个值并将其转换为日元。我想输入一串值并将每个值转换为日元。
例如,下面的代码将只转换输入的一个值,直到输入零。然后程序将不会运行。
我如何让它采用一串浮点值,例如:
34.4 4.9 34.0 9.98 0
并将其转换为日元,同时在达到零时仍终止?
import java.util.Scanner;
public class P4Point27 {
public static void main(String[] args) {
String convert = "Enter Dollars to Convert to Yen (Enter '0' to Quit): ";
Scanner in = new Scanner(System.in);
System.out.print("Enter the Price of $1.00 Dollar in Japanese Yen: ");
double dollarToYen = in.nextDouble();
System.out.print(convert);
double dollars = in.nextDouble();
while (dollars != 0) {
double price = dollars * dollarToYen;
System.out.println("$" + dollars + " is " + price + " yen.");
System.out.print(convert);
dollars = in.nextDouble();
}
in.close();
}
}
输入:
9 8 7 0
输出:
Enter the Price of $1.00 Dollar in Japanese Yen: 9 8 7 0
Enter Dollars to Convert to Yen (Enter '0' to Quit): $8.0 is 72.0 yen.
Enter Dollars to Convert to Yen (Enter '0' to Quit): $7.0 is 63.0 yen.
Enter Dollars to Convert to Yen (Enter '0' to Quit):
如您所见,它忽略了 9,并且还不断重新打印状态消息。我相信使用 do-while 循环将修复它缺少 9 或 for 循环,但我不确定。
修正了代码!工作代码!
package assignment4;
import java.util.Scanner;
public class P4Point27 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the Price of $1.00 Dollar in Japanese Yen: ");
double dollarToYen = in.nextDouble();
System.out.print("Enter a String of Numbers Seperated by a Space and Terminated by a '0' to End: ");
double dollars = in.nextDouble();
while (dollars != 0) {
while (dollars != 0) {
double price = dollars * dollarToYen;
System.out.println("$" + dollars + " is " + price + " yen.");
dollars = in.nextDouble();
}
System.out.print("Enter a String of Numbers again or '0' to quit: ");
dollars = in.nextDouble();
}
in.close();
}
}