尝试将输入的数字转换为季度,镍币,硬币和硬币。遇到一些问题:
public class Coins {
public static void main(String[] args){
private int quarters, dimes, nickels, pennies;
public void CoinsToChange(TotalCoins){
quarters = (int)(TotalCoins/25);
TotalCoins %= 25;
dimes = (int)(TotalCoins/10);
TotalCoins %= 10;
nickels = (int)(TotalCoins/5);
TotalCoins %= 5;
pennies = (int)(TotalCoins/1);
TotalCoins %= 1;
System.out.println("Quarters = " + quarters + "\nDimes = " + dimes + "\nNickels = " + nickels + "\nPennies = " + pennies);
}
}
}
这是我的测试人员类:(我在调用CoinsTotChange方法时遇到问题。)
import java.util.Scanner;
public class CoinsTester {
Coins money = new Coins();
money.CoinsToChange(changeMoney);
Scanner kybd = new Scanner(System.in);
int changeMoney = kybd.nextInt();
}
答案 0 :(得分:3)
尝试更改操作顺序。在声明/实例化之前,通常不能使用对象/变量。
Coins money = new Coins();
Scanner kybd = new Scanner(System.in);
int changeMoney = kybd.nextInt();
money.CoinsToChange(changeMoney);
答案 1 :(得分:1)
有很多语法问题,但您的整体计算是正确的。尝试这样的事情:
public class Coins {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int totalPennies = kybd.nextInt();
printMoneyAsChange(totalPennies);
}
public static void printMoneyAsChange(int pennies) {
int quarters = pennies / 25;
pennies %= 25;
int dimes = pennies / 10;
pennies %= 10;
int nickels = pennies / 5;
pennies %= 5;
System.out.println(String.format("Quarters = %d\nDimes = %d\nNickels = %d\nPennies = %d", quarters, dimes, nickels, pennies));
}
}
答案 2 :(得分:1)
以下是问题:
public void CoinsToChange(TotalCoins)
应该是public void CoinsToChange(int TotalCoins)
而不是money.CoinsToChange(changeMoney)
。changeMoney
中宣布并分配int changeMoney = kybd.nextInt()
之前致电public class Coins {
private int quarters, dimes, nickels, pennies;
public void CoinsToChange(int TotalCoins) {
quarters = (int) (TotalCoins / 25);
TotalCoins %= 25;
dimes = (int) (TotalCoins / 10);
TotalCoins %= 10;
nickels = (int) (TotalCoins / 5);
TotalCoins %= 5;
pennies = (int) (TotalCoins / 1);
TotalCoins %= 1;
System.out.println("Quarters = " + quarters + "\nDimes = " + dimes
+ "\nNickels = " + nickels + "\nPennies = " + pennies);
}
}
。你需要把它放在它之后而不是之前。尽可能少地做出更改,我让你的代码工作如下:
import java.util.Scanner;
public class CoinsTester {
public static void main(String[] args) {
Coins money = new Coins();
Scanner kybd = new Scanner(System.in);
int changeMoney = kybd.nextInt();
money.CoinsToChange(changeMoney); // This line needs to be at the bottom
}
}
测试员类:
{{1}}
注意:其他一些答案也为您提供了更好的建议,这些建议与更好的变量名称和字符串格式的使用有关。接受他们的建议会很好。我特别想解决编译器错误。
答案 3 :(得分:0)
据我所知,提供的代码存在很多问题。
在第一个代码示例中,您将在
中引入函数声明和私有字段public static void main(String [] args){}
,所以你的课程不会编译,因此你将无法从其他课程中使用它
然后,您在使用变量之前将其声明为@Tank在他的回答中建议。
它也被认为是一种很好的做法,坚持使用普遍接受的命名约定和格式。