I am new to Java, so please forgive me if it is a very small mistake,
here's my code:
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;
}
}
}
when i run it after compiling, the 18th line(n = System.in.read()) gets skipped.
The output I get is this:
Cast your vote to(1-5):
1
Enter 0 to exit, enter 1 to vote again:
Cast your vote to(1-5):
2
Enter 0 to exit, enter 1 to vote again:
Cast your vote to(1-5):
^C
The value of n
is not read()
which makes the program an infinite loop.
Thank You for your help.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…