Java - 将用户输入分配给变量/更改计数器
我对java很新,虽然我对C ++有相当基本的了解。
对于我的任务,我正在计算变化并将其分类为美国货币(即,如果你有105美分,则将其分为1美元和1美分)。
逻辑上我理解如何这样做,但我在理解java语法方面遇到了一些麻烦。我很难找到一种方法将用户输入的值分配给我的创建变量。在C ++中你只需要使用cin,但Java在这方面似乎要复杂得多。
I'm quite new to java, although I have a fairly basic knowledge of C++.
For my assignment I am counting change and sorting it into American currency (i.e., if you had 105 cents, it would divide it into one dollar and one dime).
Logically I understand how to do this, but I'm having some serious trouble understanding the java syntax. I'm having serious trouble to find a way to assign a user-inputted value to a variable of my creation. In C++ you would simply use cin, but Java seems to be a lot more complicated in this regard.
这是我到目前为止的代码:
Here is my code so far:
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的一些帮助。但是,如果您在代码中看到另一个错误,请随时指出。
I would really appreciate some help with how to assign a user-input to my variable, Money. However, if you see another error in the code, feel free to point it out.
我知道这是非常基本的东西,所以我感谢您的所有合作。
I know this is really basic stuff, so I appreciate all of your cooperation.
更改此行:
Scanner input new Scanner(System.in);
收件人:
Scanner input = new Scanner(System.in);
这应该在以下行之后而不是之前:
And this should be after line below not before:
System.out.println("Enter the amount of money in cents.");
正如您所做的那样,下面的行将从输入 int
value并将其分配给您的可变货币:
And as you did , the line below will read from input int
value and assign it to your variable money :
int money = input.nextInt();