Huglight
Huglight

Reputation: 35

Why my code has IllegalStateException Error

package findmiles;

import java.util.ArrayList;
import java.util.Scanner;

public class Findmiles {
    private ArrayList<String> city = new ArrayList<String>();
    private long[][] distance;

    public void inputCity() {
        Scanner in = new Scanner(System.in);
        while (!in.next().equals("###")) {
           city.add(in.next());
           in.close();
        }
    }
    public void inputDistance() {
        Scanner in = new Scanner(System.in);
        int i, j;
        int n = city.size();
        distance = new long[n][n];
        for (i = 0; i < city.size(); i++)
            for (j = 0; j < city.size(); j++)
                distance[i][j] = in.nextLong();
        in.close();
    }
    public long getDistance(String a, String b) {
        int n = 0, m = 0;
        for (String k : city)
            if (k.equals(a))
                n = city.indexOf(k);
        for (String j : city)
            if (j.equals(b))
                m = city.indexOf(j);
        return distance[n][m];
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Findmiles dis = new Findmiles();
        dis.inputCity();
        dis.inputDistance();
        System.out.println(dis.getDistance(in.next(), in.next()));
        in.close();

    }
}

What I want to do is to output 708 when I enter these:

Hagzou Hugzou Jigxng ### 0 1108 708 1108 0 994 708 994 0 Hagzou Jigxng

It is a program to figure out distance between two cities. First you enter some name of cities, and end with "###". Then enter a matrix of distance, when the names are the same, distance is 0. Then enter two cities's names, and return the distance between them.

Upvotes: 3

Views: 46

Answers (1)

Basil Battikhi
Basil Battikhi

Reputation: 2668

Okay, After Traversing the Code, i found that you are closing the Scanner which in inputCity() inside the loop, you need to move it outside the loop because you are closing it after each iteration which is POSSIBLY give you IllegalStateException at second iteration, there should be no problem at first iteration, but at second one it tries to get a value from closed inputstream.

so your code should be

public void inputCity() {
        Scanner in = new Scanner(System.in);
        while (!in.next().equals("###")) {
            city.add(in.next());
        }
       in.close()
    }

for inputDistance() method there should be no problem at all (at least with inputstream) because you are closing the input after all loops since if the curly brackets not added then it should take the next one statement ONLY

Upvotes: 3

Related Questions