我试图创建一个GPA计算器,但我遇到了一个问题。我正在尝试使用一个变量来存储不同的值。例如,我希望我的代码如下:
输入AP类的数量:
然后我希望用户也为每个类命名,如:
AP Class 1的名称 AP等级2的名称等等
我希望用户输入AP类的名称以及他们在该类中拥有的百分比。如何在不知道AP类数量的情况下完成此操作?
这是我的代码:
System.out.print("Enter the number of classes you have: ");
numOfClass = Keyboard.readInt();
System.out.print("Enter the amount of AP Classes: ");
numOfAP = Keyboard.readInt();
if (numOfAP > 0)
{
do
{
System.out.print("Enter the name of AP Class " + (numOfAPNamed + 1) + ": ");
nameAP = Keyboard.readString();
System.out.print("Enter grade (in percentage) of AP Class " + (numOfAPNamed + 1) + ": ");
gradeAP = Keyboard.readDouble();
System.out.println();
numOfAPNamed++;
}while (numOfAPNamed != numOfAP);
}
}
}
答案 0 :(得分:0)
最简单的方法是使用数组。尝试这样的事情:
// declarations
String[] nameAP = null;
double[] gradeAP = null;
System.out.print("Enter the number of classes you have: ");
numOfClass = Keyboard.readInt();
System.out.print("Enter the amount of AP Classes: ");
numOfAP = Keyboard.readInt();
if (numOfAP > 0)
{
// instantiation
nameAP = new String[numOfAP];
gradeAP = new double[numOfAP];
// loop
for (int numOfAPNamed = 0; numOfAPNamed < numOfAP; ++numOfAPNamed)
{
System.out.printf("Enter the name of AP Class %d: ", numOfAPNamed + 1);
// input name, percentage
nameAP[numOfAPNamed] = Keyboard.readString();
System.out.printf("Enter grade (in percentage) of AP Class %d: ", numOfAPNamed + );
gradeAP[numOfAPNamed] = Keyboard.readDouble();
System.out.println();
}
// TODO process...
}
如果您事先无法知道尺寸,例如从文件中读取,则使用集合,例如List
或Map
。有关详细信息,请参阅Java Collection Framework文档...