我是Java新手,所以如果这是一个很小的错误,请原谅我,这是
我的代码:
import java.io.*;
public class election
{
public static void main(String args[])
{
boolean x=false;
Ballot ballot=new Ballot();
int n;
while(x!=true)
{
System.out.println("Cast your vote to(1-5): ");
try
{
n=System.in.read();
System.out.flush();
ballot.add(n);
System.out.println("Enter 0 to exit, enter 1 to vote again: ");
n = System.in.read();
if(n==0)
{
x=true;
}
else
{
x=false;
}
}
catch(IOException e)
{
System.out.println("I/O Error");
System.exit(1);
}
}
}
}
class Ballot
{
int votes,spoilt;
int cand[] = new int[5];
//methods
void add(int n)
{
votes=votes+1;
if(n <= 5 && n>=1)
{
cand[n-1]=cand[n-1]+1;
}
else
{
spoilt = spoilt + 1;
}
}
void display()
{
System.out.println("Total votes cast: " + votes);
for(int i=0;i<5;i++)
{
System.out.println("Candidate " + (i+1) + ": " + cand[i]);
}
System.out.println("Spoilt: " + spoilt);
System.out.println("Valid votes: " + (votes-spoilt));
}
Ballot()
{
votes=0;
spoilt=0;
for(int i=0;i<5;i++)
{
cand[i]=0;
}
}
}
当我在编译后运行它时,第 18 行(n = System.in.read()) 被跳过。
我得到的输出是这样的:
投票给(1-5):
1 输入0退出,输入1再次投票:
投票给(1-5):
2输入0退出,输入1再次投票:
投票给(1 -5):
^C
的值n
不是read()
使程序成为无限循环。
感谢您的帮助。