2

I am new to java programming , and i am trying to learn the usage of classes and objects in java programming , while writing the following code i got an exception

java.util.NoSuchElementException

for sample input

5

1 2 3 4 5

here first line contains number of elements (in this case its 5),and next line contains elements.

while taking input inside the for loop in the class Election ,i am getting exception.

I tried searching on stack Overflow, and other resources too,but still can't figure out how to remove this exception.

import java.io.*;
import java.util.Scanner;
public class TestClass {
     public static void main(String[] args) {
        int n;
        Scanner input = new Scanner(System.in);
        n = input.nextInt();
        input.nextLine();
        Election obj = new Election(n);
        obj.getVotes();
    }
}
class Election {
     int n,v1,v2,v3,v4,v5,d;
     public Election(int n) {
          this.n = n;
          v1=v2=v3=v4=v5=d=0;
     }
     public void getVotes() {
       Scanner sc = new Scanner(System.in);
       for(int i = 0 ; i < 1 ; i++) {
         int var = sc.nextInt();
         switch(var) {
             case 1: ++v1; break;
             case 2: ++v2; break;
             case 3: ++v3; break;
             case 4: ++v4; break;
             case 5: ++v5; break;
           default: ++d; break;
         }
       }     
     }
}
Ayush Mishra
  • 267
  • 3
  • 14
  • I can't reproduce your issue with the code you posted. Did you post the code as you have it in your IDE? Are you closing your `Scanner`s somewhere (cause you shouldn't)? Some small (unrelated) remarks: `v1=v2=v3=v4=v5=d=0;` is redundant since `int` fields are defaulted to `0`. And your `n` is not used anywhere. – TiiJ7 Jan 17 '19 at 14:03
  • @TiiJ7, in for loop the condition should be (i – Ayush Mishra Jan 17 '19 at 14:08
  • Like I said, you should _not_ close the `Scanner`s in this case, since that would close `System.in`. It would probably be better to reuse the same Scanner, though. Anyway, I can reproduce your problem [in ideone](https://ideone.com/G5JTke), but not in Eclipse. What IDE are you using? – TiiJ7 Jan 17 '19 at 14:20
  • @AyushMishra I have posted a late answer, but check it out anyway. It might help you understand how to extend the re-usability and functionality of your program. If there is something in the changes that is unclear to you, let me know so I can improve my solution – Soutzikevich Jan 17 '19 at 15:08
  • @AyushMishra Thanks for accepting my answer as the preferred solution. Please consider up-voting as well :) Cheers. – Soutzikevich Jan 17 '19 at 15:43
  • @P. Soutzikevich , i can't upvote since i am new to stack overflow, i have reputation less than 15,i joined today. – Ayush Mishra Jan 17 '19 at 16:09
  • @AyushMishra No worries buddy. Welcome to stack overflow! – Soutzikevich Jan 17 '19 at 16:14

3 Answers3

1

I think the code that you posted is missing. The code you posted is working properly and I achieved to get exception only when I wrote input.close() before the obj.getVotes(). When you want to close scanners you should do this after code finishes. Thus, if you close input after the obj.getVotes() you shouldn't get any error.

Y.Kakdas
  • 833
  • 7
  • 17
1

Looks like I'm a bit late, but since your accepted answer is more of comment rather than a solution, I'll post this anyway.

Here is a simple deviation of the code you provided, but reaches the desired result!

I'll walk you through this:

public class MyTest {
    public static void main(String[] args) {

        //First of all, we need an instance of an Election-type object, so
        //that we can call its methods and get votes from users.
        Election e = new Election();
        //Now we can easily call the method getVotes(), as defined in Election class.
        //What happens here, is that the program will 'jump' to the getVotes() method
        //and it will execute every line of code in that method. Then it will
        //'return' to where it 'left off' in the main() method. Since getVotes()
        //is of type 'void', it will not return anything. It will just 'jump' back.
        e.getVotes();

        //Now, you can use testResult() method, to see the values of the variables.
        e.testResult();
    }
}

Now, let's take a look at the class Election and how it works.

public class Election {
    private final int VOTES_NUM = 1;
    private int v1,v2,v3,v4,v5,d;

    public Election() {
        v1=v2=v3=v4=v5=d=0;
        //print now, just to show that all variables = 0
        testResult();
    }

    //Simple method that prints value of each variable. We use this for testing
    public void testResult(){
        System.out.println("v1 = "+v1);
        System.out.println("v2 = "+v2);
        System.out.println("v3 = "+v3);
        System.out.println("v4 = "+v4);
        System.out.println("v5 = "+v5);
        System.out.println("d = "+d);
    }

    private int getInput(){
       //First of all, we need a Scanner to take user input. 
       //You do that in your own code too. We simply move it in this method instead.
        Scanner input = new Scanner(System.in);

        //You also need variable to hold the user input. 
        //(Always give meaningful names to all entities)
        int userInput;

        System.out.print("Please enter vote number here: ");

        //the next part has to be in a try-catch block, 
        //to avoid exceptions like InputMismatchException, etc..
        try{
            //Get user input
            userInput = input.nextInt();
        }
        //If user enters letter, or symbol, or something else that isn't an integer,
        //then inform them of the mistake they made and recursively call this method,
        //until they get it right!
        catch (InputMismatchException ime){
            System.out.println("Please enter only a single number");
            return getInput();
        }

        //If all goes well, return the user input
        return userInput;
    }

    public void getVotes() {
        //'VOTES_NUM' is a constant that defines the times the 
        //loop will iterate (like Macros in 'C')
        for(int x=0; x<VOTES_NUM; x++)
            int n = getInput();
        //then let the switch statement increment one of the variables
        switch(userInput) {
            case 1: ++v1; break;
            case 2: ++v2; break;
            case 3: ++v3; break;
            case 4: ++v4; break;
            case 5: ++v5; break;
            default: ++d; break;
        }
    }
}
Soutzikevich
  • 991
  • 3
  • 13
  • 29
0

I tried running your code in a short main class, and I am not getting any exception. This is how I ran your method:

public static  void main(String...args){
    Election election = new Election(10);
    election.getVotes();
    System.out.println(election.v1);
    System.out.println(election.v2);
    System.out.println(election.v3);
    System.out.println(election.v4);
    System.out.println(election.v5);
    System.out.println(election.d);
}

My input was 1 2 3 4 5 6 7 1 2 2 and the console output was:

2 // v1
3 // v2
1 // v3
1 // v4
1 // v5
2 // d

I did make a small change to your program. In the for loop inside the getVotes() method, I changed the condition to i<n (instead of i<1 in your posted code)

FrenchFigaro
  • 371
  • 2
  • 18
  • i typed by mistake that condition..(i – Ayush Mishra Jan 17 '19 at 14:02
  • You edited your post since I pasted it my IDE, I'll give it another try – FrenchFigaro Jan 17 '19 at 14:04
  • @AyushMishra I copied and pasted it exactly in my IDE again, and I am still not getting any Exception. – FrenchFigaro Jan 17 '19 at 14:08
  • @FrenchFiagro, i don't know why you are not getting any exception,but as we can't create two scanner objects at same time using System.in,if i need to use multiple Scanner objects i should close the previous one otherwise exception comes.**https://stackoverflow.com/questions/4232588/how-to-use-multiple-scanner-objects-on-system-in** – Ayush Mishra Jan 17 '19 at 14:14
  • @AyushMishra Why would you need to use multiple `Scanner()`-type objects my friend? – Soutzikevich Jan 17 '19 at 15:11