Note that there are some explanatory texts on larger screens.

plurals
  1. POSystem.in.read() does not read
    primarykey
    data
    text
    <p>I am new to Java, so please forgive me if it is a very small mistake,<br> here's my code:</p> <pre><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 &lt;= 5 &amp;&amp; n&gt;=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&lt;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&lt;5;i++) { cand[i]=0; } } } </code></pre> <p>when i run it after compiling, the 18th line(n = System.in.read()) gets skipped. <br>The output I get is this:</p> <blockquote> <p>Cast your vote to(1-5):<br> 1 Enter 0 to exit, enter 1 to vote again:<br> Cast your vote to(1-5):<br> 2 Enter 0 to exit, enter 1 to vote again:<br> Cast your vote to(1-5):<br> ^C</p> </blockquote> <p>The value of <code>n</code> is not <code>read()</code> which makes the program an infinite loop.</p> <p>Thank You for your help.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload