How to use multiple scanners of different types in java?












0















I have this code in Java (executed on the default Eclipse console) :



String name = "";
System.out.printf("Name of the Story Arc: ");

if(in.hasNext()) {
name = in.nextLine();
}

int l = 0;
System.out.printf("Length of the Story Arc: ");
if(in.hasNextInt()) {
l = in.nextInt();
}

StoryArc a = new StoryArc(name, id, issues_nb + 1, l);
story_arcs.add(a);


I am trying to execute it multiple times in a row but it behaves weirdly :
The first execution works fine, asking the name, then the length. The second execution, it asks the name, but not the length (set to 0). The third execution asks the length, but sets the name to "", and it loops like that, with length on even executions and name on odd ones.



It's one of my first program in Java so I suppose I didn't understand something with scanners, but I couldn't figure it out after long researches, so please help.



edit:
Thank you all! With you help we managed to make it work!










share|improve this question




















  • 2





    can you please post your full code?

    – GauravRai1512
    Nov 16 '18 at 10:02
















0















I have this code in Java (executed on the default Eclipse console) :



String name = "";
System.out.printf("Name of the Story Arc: ");

if(in.hasNext()) {
name = in.nextLine();
}

int l = 0;
System.out.printf("Length of the Story Arc: ");
if(in.hasNextInt()) {
l = in.nextInt();
}

StoryArc a = new StoryArc(name, id, issues_nb + 1, l);
story_arcs.add(a);


I am trying to execute it multiple times in a row but it behaves weirdly :
The first execution works fine, asking the name, then the length. The second execution, it asks the name, but not the length (set to 0). The third execution asks the length, but sets the name to "", and it loops like that, with length on even executions and name on odd ones.



It's one of my first program in Java so I suppose I didn't understand something with scanners, but I couldn't figure it out after long researches, so please help.



edit:
Thank you all! With you help we managed to make it work!










share|improve this question




















  • 2





    can you please post your full code?

    – GauravRai1512
    Nov 16 '18 at 10:02














0












0








0








I have this code in Java (executed on the default Eclipse console) :



String name = "";
System.out.printf("Name of the Story Arc: ");

if(in.hasNext()) {
name = in.nextLine();
}

int l = 0;
System.out.printf("Length of the Story Arc: ");
if(in.hasNextInt()) {
l = in.nextInt();
}

StoryArc a = new StoryArc(name, id, issues_nb + 1, l);
story_arcs.add(a);


I am trying to execute it multiple times in a row but it behaves weirdly :
The first execution works fine, asking the name, then the length. The second execution, it asks the name, but not the length (set to 0). The third execution asks the length, but sets the name to "", and it loops like that, with length on even executions and name on odd ones.



It's one of my first program in Java so I suppose I didn't understand something with scanners, but I couldn't figure it out after long researches, so please help.



edit:
Thank you all! With you help we managed to make it work!










share|improve this question
















I have this code in Java (executed on the default Eclipse console) :



String name = "";
System.out.printf("Name of the Story Arc: ");

if(in.hasNext()) {
name = in.nextLine();
}

int l = 0;
System.out.printf("Length of the Story Arc: ");
if(in.hasNextInt()) {
l = in.nextInt();
}

StoryArc a = new StoryArc(name, id, issues_nb + 1, l);
story_arcs.add(a);


I am trying to execute it multiple times in a row but it behaves weirdly :
The first execution works fine, asking the name, then the length. The second execution, it asks the name, but not the length (set to 0). The third execution asks the length, but sets the name to "", and it loops like that, with length on even executions and name on odd ones.



It's one of my first program in Java so I suppose I didn't understand something with scanners, but I couldn't figure it out after long researches, so please help.



edit:
Thank you all! With you help we managed to make it work!







java input






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 21:26







Victor Fanton

















asked Nov 16 '18 at 9:58









Victor FantonVictor Fanton

15




15








  • 2





    can you please post your full code?

    – GauravRai1512
    Nov 16 '18 at 10:02














  • 2





    can you please post your full code?

    – GauravRai1512
    Nov 16 '18 at 10:02








2




2





can you please post your full code?

– GauravRai1512
Nov 16 '18 at 10:02





can you please post your full code?

– GauravRai1512
Nov 16 '18 at 10:02












3 Answers
3






active

oldest

votes


















0














Try this.Your code has no problem but after you can run this may be it will help you



import java.util.*;

public class Answer {


public static void main(String args) {

String name = "";
System.out.printf("Name of the Story Arc: ");
Scanner in = new Scanner(System.in);
if(in.hasNext()) {
name = in.nextLine();
}

int l = 0;
System.out.printf("Length of the Story Arc: ");
if(in.hasNextInt()) {
l = in.nextInt();
}

System.out.println("Name of the Story Arc: "+name);
System.out.println("Length of the Story Arc: "+l);


}

}





share|improve this answer































    0














    l = in.nextInt() will only get the integer, but doesn't indicate you're done inputting that line, so you'll have to tell the Scanner that yourself. There are two ways to do this:



    You can do a in.nextLine(); to indicate we're done with the line containing the integer:



    Change l = in.nextInt(); to:



    l = in.nextInt();
    if(in.hasNext()){
    // Ignore the rest of the line that contained the length integer-input:
    in.nextLine();
    }


    Try it online.



    Alternatively, you can use in.nextLine() for all your inputs, and convert the String to an integer yourself:



    Change l = in.nextInt(); to:



    String input = in.nextLine();
    // Verify the entire line only contains the integer:
    if(input.matches("\d+")){
    l = Integer.parseInt(input);
    } else{
    // TODO: Validation message: not a valid integer
    }


    Try it online.






    share|improve this answer































      0














      You need a while loop to get a valid name and also

      you need a while loop with try/catch to get l, because the user could input an invalid value instead of a valid integer:



      String name = "";
      while (name.trim().length() == 0) {
      System.out.print("Name of the Story Arc: ");
      name = in.nextLine();
      }

      int l = 0;
      boolean valid = false;
      while (!valid) {
      try {
      System.out.print("Length of the Story Arc: ");
      l = in.nextInt();
      valid = (l > 0);
      } catch (Exception e) {
      e.printStackTrace();
      }
      }





      share|improve this answer


























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335394%2fhow-to-use-multiple-scanners-of-different-types-in-java%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        Try this.Your code has no problem but after you can run this may be it will help you



        import java.util.*;

        public class Answer {


        public static void main(String args) {

        String name = "";
        System.out.printf("Name of the Story Arc: ");
        Scanner in = new Scanner(System.in);
        if(in.hasNext()) {
        name = in.nextLine();
        }

        int l = 0;
        System.out.printf("Length of the Story Arc: ");
        if(in.hasNextInt()) {
        l = in.nextInt();
        }

        System.out.println("Name of the Story Arc: "+name);
        System.out.println("Length of the Story Arc: "+l);


        }

        }





        share|improve this answer




























          0














          Try this.Your code has no problem but after you can run this may be it will help you



          import java.util.*;

          public class Answer {


          public static void main(String args) {

          String name = "";
          System.out.printf("Name of the Story Arc: ");
          Scanner in = new Scanner(System.in);
          if(in.hasNext()) {
          name = in.nextLine();
          }

          int l = 0;
          System.out.printf("Length of the Story Arc: ");
          if(in.hasNextInt()) {
          l = in.nextInt();
          }

          System.out.println("Name of the Story Arc: "+name);
          System.out.println("Length of the Story Arc: "+l);


          }

          }





          share|improve this answer


























            0












            0








            0







            Try this.Your code has no problem but after you can run this may be it will help you



            import java.util.*;

            public class Answer {


            public static void main(String args) {

            String name = "";
            System.out.printf("Name of the Story Arc: ");
            Scanner in = new Scanner(System.in);
            if(in.hasNext()) {
            name = in.nextLine();
            }

            int l = 0;
            System.out.printf("Length of the Story Arc: ");
            if(in.hasNextInt()) {
            l = in.nextInt();
            }

            System.out.println("Name of the Story Arc: "+name);
            System.out.println("Length of the Story Arc: "+l);


            }

            }





            share|improve this answer













            Try this.Your code has no problem but after you can run this may be it will help you



            import java.util.*;

            public class Answer {


            public static void main(String args) {

            String name = "";
            System.out.printf("Name of the Story Arc: ");
            Scanner in = new Scanner(System.in);
            if(in.hasNext()) {
            name = in.nextLine();
            }

            int l = 0;
            System.out.printf("Length of the Story Arc: ");
            if(in.hasNextInt()) {
            l = in.nextInt();
            }

            System.out.println("Name of the Story Arc: "+name);
            System.out.println("Length of the Story Arc: "+l);


            }

            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 16 '18 at 12:04









            flopcoderflopcoder

            777513




            777513

























                0














                l = in.nextInt() will only get the integer, but doesn't indicate you're done inputting that line, so you'll have to tell the Scanner that yourself. There are two ways to do this:



                You can do a in.nextLine(); to indicate we're done with the line containing the integer:



                Change l = in.nextInt(); to:



                l = in.nextInt();
                if(in.hasNext()){
                // Ignore the rest of the line that contained the length integer-input:
                in.nextLine();
                }


                Try it online.



                Alternatively, you can use in.nextLine() for all your inputs, and convert the String to an integer yourself:



                Change l = in.nextInt(); to:



                String input = in.nextLine();
                // Verify the entire line only contains the integer:
                if(input.matches("\d+")){
                l = Integer.parseInt(input);
                } else{
                // TODO: Validation message: not a valid integer
                }


                Try it online.






                share|improve this answer




























                  0














                  l = in.nextInt() will only get the integer, but doesn't indicate you're done inputting that line, so you'll have to tell the Scanner that yourself. There are two ways to do this:



                  You can do a in.nextLine(); to indicate we're done with the line containing the integer:



                  Change l = in.nextInt(); to:



                  l = in.nextInt();
                  if(in.hasNext()){
                  // Ignore the rest of the line that contained the length integer-input:
                  in.nextLine();
                  }


                  Try it online.



                  Alternatively, you can use in.nextLine() for all your inputs, and convert the String to an integer yourself:



                  Change l = in.nextInt(); to:



                  String input = in.nextLine();
                  // Verify the entire line only contains the integer:
                  if(input.matches("\d+")){
                  l = Integer.parseInt(input);
                  } else{
                  // TODO: Validation message: not a valid integer
                  }


                  Try it online.






                  share|improve this answer


























                    0












                    0








                    0







                    l = in.nextInt() will only get the integer, but doesn't indicate you're done inputting that line, so you'll have to tell the Scanner that yourself. There are two ways to do this:



                    You can do a in.nextLine(); to indicate we're done with the line containing the integer:



                    Change l = in.nextInt(); to:



                    l = in.nextInt();
                    if(in.hasNext()){
                    // Ignore the rest of the line that contained the length integer-input:
                    in.nextLine();
                    }


                    Try it online.



                    Alternatively, you can use in.nextLine() for all your inputs, and convert the String to an integer yourself:



                    Change l = in.nextInt(); to:



                    String input = in.nextLine();
                    // Verify the entire line only contains the integer:
                    if(input.matches("\d+")){
                    l = Integer.parseInt(input);
                    } else{
                    // TODO: Validation message: not a valid integer
                    }


                    Try it online.






                    share|improve this answer













                    l = in.nextInt() will only get the integer, but doesn't indicate you're done inputting that line, so you'll have to tell the Scanner that yourself. There are two ways to do this:



                    You can do a in.nextLine(); to indicate we're done with the line containing the integer:



                    Change l = in.nextInt(); to:



                    l = in.nextInt();
                    if(in.hasNext()){
                    // Ignore the rest of the line that contained the length integer-input:
                    in.nextLine();
                    }


                    Try it online.



                    Alternatively, you can use in.nextLine() for all your inputs, and convert the String to an integer yourself:



                    Change l = in.nextInt(); to:



                    String input = in.nextLine();
                    // Verify the entire line only contains the integer:
                    if(input.matches("\d+")){
                    l = Integer.parseInt(input);
                    } else{
                    // TODO: Validation message: not a valid integer
                    }


                    Try it online.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 16 '18 at 10:16









                    Kevin CruijssenKevin Cruijssen

                    5,02273989




                    5,02273989























                        0














                        You need a while loop to get a valid name and also

                        you need a while loop with try/catch to get l, because the user could input an invalid value instead of a valid integer:



                        String name = "";
                        while (name.trim().length() == 0) {
                        System.out.print("Name of the Story Arc: ");
                        name = in.nextLine();
                        }

                        int l = 0;
                        boolean valid = false;
                        while (!valid) {
                        try {
                        System.out.print("Length of the Story Arc: ");
                        l = in.nextInt();
                        valid = (l > 0);
                        } catch (Exception e) {
                        e.printStackTrace();
                        }
                        }





                        share|improve this answer






























                          0














                          You need a while loop to get a valid name and also

                          you need a while loop with try/catch to get l, because the user could input an invalid value instead of a valid integer:



                          String name = "";
                          while (name.trim().length() == 0) {
                          System.out.print("Name of the Story Arc: ");
                          name = in.nextLine();
                          }

                          int l = 0;
                          boolean valid = false;
                          while (!valid) {
                          try {
                          System.out.print("Length of the Story Arc: ");
                          l = in.nextInt();
                          valid = (l > 0);
                          } catch (Exception e) {
                          e.printStackTrace();
                          }
                          }





                          share|improve this answer




























                            0












                            0








                            0







                            You need a while loop to get a valid name and also

                            you need a while loop with try/catch to get l, because the user could input an invalid value instead of a valid integer:



                            String name = "";
                            while (name.trim().length() == 0) {
                            System.out.print("Name of the Story Arc: ");
                            name = in.nextLine();
                            }

                            int l = 0;
                            boolean valid = false;
                            while (!valid) {
                            try {
                            System.out.print("Length of the Story Arc: ");
                            l = in.nextInt();
                            valid = (l > 0);
                            } catch (Exception e) {
                            e.printStackTrace();
                            }
                            }





                            share|improve this answer















                            You need a while loop to get a valid name and also

                            you need a while loop with try/catch to get l, because the user could input an invalid value instead of a valid integer:



                            String name = "";
                            while (name.trim().length() == 0) {
                            System.out.print("Name of the Story Arc: ");
                            name = in.nextLine();
                            }

                            int l = 0;
                            boolean valid = false;
                            while (!valid) {
                            try {
                            System.out.print("Length of the Story Arc: ");
                            l = in.nextInt();
                            valid = (l > 0);
                            } catch (Exception e) {
                            e.printStackTrace();
                            }
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 16 '18 at 10:27

























                            answered Nov 16 '18 at 10:21









                            forpasforpas

                            19k3828




                            19k3828






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335394%2fhow-to-use-multiple-scanners-of-different-types-in-java%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Xamarin.iOS Cant Deploy on Iphone

                                Glorious Revolution

                                Dulmage-Mendelsohn matrix decomposition in Python