【发布时间】:2013-10-12 23:32:47
【问题描述】:
我知道这个问题已经被问过很多次了,但我仍然无法解决这个问题。问题是我必须存储用户输入并打印出一个值。
例如,有 4 个人,person1、person2、person3 和 person4。如果我投给person1,则person1的票数变为1,其他人保持为0。那么如果我投给person2,则person2的票数变为1,而person1也为1。
我可以编译代码。但是如果我投票给 person1,输出变成 4。如果我再投票给 person2,person2 的输出变成 4,投票给 person1 又回到 0。我是一个完全的编程初学者,在这个程序中被卡住了整整 4 天,非常感谢任何帮助。非常感谢您提前。
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
public static void main (String[] args)
{
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Initialize String Arrays
String[] person = new String[4];
person[0] = "person1";
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
int[] votescount = new int[4];
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
int i;
for (i=0; i<votescount.length; i++)
{
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
} // end for loop
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
【问题讨论】:
-
考虑学习如何使用调试器。
-
在java中,方法名应该是驼峰式
-
这不只是语法的一种方式吗?
-
@user2875021 您拥有方法名称的方式不会导致任何错误,但标准是驼峰式。它更易于阅读,看起来更专业,但您不必这样做。
标签: java