尽管我对 C++ 有相当基本的了解,但我对 java 还很陌生。
在我的作业中,我计算零钱并将其分类为美国货币(即,如果您有 105 美分,它将分为 1 美元和 1 毛钱)。
从逻辑上讲,我明白如何做到这一点,但我在理解 java 语法时遇到了一些严重的困难。我在寻找一种将用户输入的值分配给我创建的变量的方法时遇到了严重的麻烦。在 C++ 中,您只需使用 cin,但 Java 在这方面似乎要复杂得多。
这是迄今为止我的代码:
package coinCounter;
import KeyboardPackage.Keyboard;
import java.util.Scanner;
public class helloworld
{
public static void main(String[] args)
{
Scanner input new Scanner(System.in);
//entire value of money, to be split into dollars, quarters, etc.
int money = input.nextInt();
int dollars = 0, quarters = 0, dimes = 0, nickels = 0;
//asks for the amount of money
System.out.println("Enter the amount of money in cents.");
//checking for dollars, and leaving the change
if(money >= 100)
{
dollars = money / 100;
money = money % 100;
}
//taking the remainder, and sorting it into dimes, nickels, and pennies
else if(money > 0)
{
quarters = money / 25;
money = money % 25;
dimes = money / 10;
money = money % 10;
nickels = money / 5;
money = money % 5;
}
//result
System.out.println("Dollars: " + dollars + ", Quarters: " + quarters + ", Dimes: " + dimes + ", Nickels: " + nickels + ", Pennies: " + money);
}
}
我非常感谢有关如何将用户输入分配给我的变量 Money 的帮助。但是,如果您在代码中看到其他错误,请随时指出。
我知道这确实是基本的东西,所以我感谢您的合作。
最佳答案
更改此行:
Scanner input new Scanner(System.in);
致:
Scanner input = new Scanner(System.in);
这应该在下面的行之后而不是之前:
System.out.println("Enter the amount of money in cents.");
正如您所做的那样,下面的行将从输入 int
值中读取并将其分配给您的变量 Money :
int money = input.nextInt();
关于Java - 将用户输入分配给变量/更改计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18583106/