Java - Assigning User Input to Variable / Change Counter

我们两清 提交于 2019-12-04 05:21:22

问题


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);

    }

}

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.


回答1:


Change this line :

Scanner input new Scanner(System.in);

To :

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.");

And as you did , the line below will read from input int value and assign it to your variable money :

int money = input.nextInt();


来源:https://stackoverflow.com/questions/18583106/java-assigning-user-input-to-variable-change-counter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!