0

I'm new to Java. I want to get loop input except when the user inputs 0 that terminates the program in Java. I know how to implement this in C++ (as shown below), but the Java code I wrote doesn't work.

C++:

while (cin >> n, n) {
    GraphAdjList G;
    CreateAdjListGraph(G, n);
    n = 0;
}

Java:

Scanner sc = new Scanner(System. in );
n = sc.nextInt();
while (n != 0) {
    Graph G = new Graph();
    G.CreateAdjListGraph(n);
    //G.print();
    n = sc.nextInt();
}

This is what I want. The program terminates only when the user inputs 0.

2
qRj dIm
aTy oFu
4
qRj aTy
qRj oFu
oFu cLq
aTy qUr
0
karel
  • 5,489
  • 46
  • 45
  • 50
superman22
  • 13
  • 1
  • 1
    Define "didn't work". What are yo doing **precisely**, what do you expect to happen, and what happens instead? – JB Nizet Mar 23 '19 at 07:53
  • it throws Exception in thread "main" java.util.NoSuchElementException – superman22 Mar 23 '19 at 07:55
  • I cannot continue to input more "n" in this program – superman22 Mar 23 '19 at 07:56
  • 1
    You're probably closing System.in somewhere inside CreateAdjListGraph. What are you typing? What does this method do? – JB Nizet Mar 23 '19 at 08:00
  • The Problem seems to be somewhere inside CreateAdjListGraph(n); – Adnan Ahmad Khan Mar 23 '19 at 08:17
  • This a Graph problem. the n indicate this graph has n edges, in CreateAdjListGraph() method, the user input n sets of edges like"A B"\n "A C",than I put this edges in my class and create a digraph. I use another Scanner in this method and closed it when I'm done. In this method I deleted all print statement but the problem remains – superman22 Mar 23 '19 at 08:33
  • @superman22 Please [edit] your question to include a [mcve], which can be compiled and tested by others. Also include the full exception message you get. And please check https://stackoverflow.com/questions/13042008/java-util-nosuchelementexception-scanner-reading-user-input. – Progman Mar 23 '19 at 10:35

2 Answers2

0

nextInt() won't work for your case, If your input contains a non-integer word it throws InputMismatchException. You better use nextLine() and try to convert each word in to int with Integer.parseInt.

For example:

        int n = -1;
        Scanner sc = new Scanner(System.in);
        String line;

        while (n != 0){
            line = sc.nextLine();
            String[] splits = line.split(" ");
            System.out.println(Arrays.toString(splits));

            for (String split : splits) {
                try {
                    n = Integer.parseInt(split);
                    if (n == 0)
                        break;
                    //Graph G = new Graph();
                    //G.CreateAdjListGraph(n);

                } catch (NumberFormatException e) {
                    // handling
                }
            }
        }

This should work even if you give all inputs in the same line.

HariUserX
  • 1,341
  • 1
  • 9
  • 17
  • thank you! But it didn't work either. it throws java.util.NoSuchElementException I think it's because it the while loop I used println and the Scanner receive the newline rather than waiting for my input – superman22 Mar 23 '19 at 08:05
  • Added an example. Check now. – HariUserX Mar 23 '19 at 08:06
  • Thank you!I found My Bug, it's because i used another Scanner in a method and turn it down. Now I know that you only need to close scanner once. – superman22 Mar 25 '19 at 06:55
0

You should not use scan.nextInt() because in your sample program run you took some non-inetger values as input, so, in that case you code will fail.

Use scan.nextLine() this will take argument as String and not as Integer. Now you can change compare the results for your While loop.

Working Code:

import java.util.Scanner;
public class stackScanner
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        String input = scan.nextLine();

        // as you are now taking "String" from user so you have to compare it with "0" not 0
        while(!(input.equals("0")))  // while input is not 0
        {
            // your code here
            input = scan.nextLine();
        }
    }
}

Note: I am using String.equals() and not == operator, reasons:

  • As String.equals() always return boolean value it doesn't through any exception.
  • We can use == operators for reference comparison (address comparison) and Stinrg.equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas String.equals() evaluates to the comparison of values in the objects.

For more on String.equals()

Zain Arshad
  • 1,885
  • 1
  • 11
  • 26
  • Thank you! But i am so sorry that I didn't write clearly in my question. when I want user to type a int, there is only this int on the currently line. It's more like this 3\n A B\n C D\n C B\n 0\n and the program terminates – superman22 Mar 23 '19 at 08:26
  • where \n means the following is on a newline – superman22 Mar 23 '19 at 08:27
  • I don't understand actually what you want to do with this code? You want to take input as long as user inputs "0", then your while-loop should terminate. My code is exactly doing this. However, a little more information is required so that I can solve your problem. – Zain Arshad Mar 23 '19 at 08:30
  • This a Graph problem. the n indicate this graph has n edges, in CreateAdjListGraph() method, the user input n sets of edges like"A B"\n "A C",than I put this edges in my class and create a digraph. I use another Scanner in this method and closed it when I'm done. In this method I deleted all print statement but the problem remains – superman22 Mar 23 '19 at 08:36
  • It's an Online Judge title. It wants this way to check more samples during one inputs. I thought this is an popular way when coding in OJ – superman22 Mar 23 '19 at 08:39
  • There is still some ambiguity on how you are achieving this. See this, you are using `CreateAdjListGraph(n)` to add the edge, then you should only take one `String` input at a time with out any `space` between them. As you are saving the input in `n`. What I think your input should be like "A\n B\n E\n R\n" and not like this "A B"\n "A C. – Zain Arshad Mar 23 '19 at 08:53