Java:Int无法转换为变量,而变量无法转换为int

时间:2017-10-23 19:36:50

标签: java

我正在尝试使用while语句以及使用扫描程序在Java中创建货币转换器。我以为我已经设置了但是它说int不能转换为我的变量(meme)而且变量(meme)不能转换为int。

import java.util.Scanner;
public class MemeRunner
{
    public static void main (String[] args)
    {
        int currency;
        Scanner sc =new Scanner(System.in);
        Meme m = sc.nextInt();


        System.out.println("Welcome to Currency Converter! ");
        System.out.print("Enter your currency ");

        while(currency >= 0)
        {
            System.out.println(currency);
            currency = sc.nextInt(m);
        }
        System.out.println("Change Maker Program");

        Meme coin = new Meme(99);
        System.out.println(coin);

        Meme change = new Meme(41);
        System.out.println(change);

        Meme money = new Meme(33);
        System.out.println(money);
    }
}

这是我的公共课。第一个是跑步者。也许这会提供更多信息。

public class Meme
{
    private int totalCents;

    public Meme()
    {
        totalCents = 0;
    }

    public Meme(int cents)
    {
        totalCents = cents;
    }

    public int getDollars ()
    {
        int dollars;
        dollars = totalCents / 100;
        totalCents = totalCents % 100;
        return dollars;
    }

    public int getQuarters ()
    {
        int quarters;
        quarters = totalCents / 25;
        totalCents = totalCents % 25;
        return quarters;
    }

    public int getDimes ()
    {
        int dimes;
        dimes = totalCents / 10;
        totalCents = totalCents % 10;
        return dimes;
    }

    public int getNickels ()
    {
        int nickels;
        nickels = totalCents / 5;
        totalCents = totalCents % 5;
        return nickels;
    }

    public int getPennies ()
    {
        int pennies;
        pennies = totalCents;
        return pennies;
    }

    public String toString()
    {
        String result = "Total Currency: " + totalCents + "\n ";
        result += "Dollars: " + getDollars() + "\n ";
        result += "Quarters: " + getQuarters() + "\n ";
        result += "Dimes: " + getDimes() + "\n ";
        result += "Nickels: " + getNickels() + "\n ";
        result += "Pennies: " + getPennies() + "\n ";
        return result;
    }
}  

1 个答案:

答案 0 :(得分:0)

您的Meme类有一个构造函数,它接受一个int。所以你应该能够做到:

Meme m = new Meme(sc.nextInt());

此对象m需要被视为对象。因此,你不能像int一样使用它。所以你不能做currency = sc.nextInt(m);,并且必须用以下内容替换它:

currency = sc.nextInt(m.getValue()); // replace getValue() with whatever the name of your method is

旁注(编辑Meme课程后):您的get...似乎缺乏一致性。所有这些都会减少totalCents 的数量,除了 getPennies,它会保留调用前后的数量。我不知道这是否是所希望的行为,但我不相信,因为这意味着调用toString方法只会减少totalCents中仅用于打印的金额。

相关问题