Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

java - System.in.read() does not read

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think it would be easier if you made use of the Scanner class. You can instantiate a scanner object like so Scanner scan = new Scanner(System.in);. Then line 18 can become n = scan.nextInt(); This should properly read the user input. For more information on the Scanner class see the Java docs: http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html. Hope this helped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...