PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How to make CTRL+Z NOT mess up a java console program

 October 30, 2022     console, eclipse, eof, java, nosuchelementexception     No comments   

Issue

One of my final project requirements is that, if it is console based which mine is, entering ctrl + z WON'T mess up the program. The nextLine() statement from my scanner is within a while loop, and when I try to catch the NoSuchElementException from entering ctrl+z, the error message in the catch block loops endlessly.

        while (!advanceTurn) {

        System.out.print("\nCommand: ");

        try {input = s.nextLine();}
        catch (NoSuchElementException e) {

            System.out.println("Use the EXIT command to exit the game.");
            s = new Scanner(System.in);
            input = "asdfjkl;";
            continue;

        }

        System.out.println();

        // This takes the input and decides what command was entered (if any) and deals
        // with it appropriately.
        parseCommand(input);

    }

As you can see in the code, I've tried to re-initialize the scanner when the error is caught, and then jump back to the beginning of the loop so a new line can be grabbed, but it appears that the error still persists even when there's no new input from the keyboard, so I'm pretty much stumped as to how to solve this. Any help is appreciated, thanks.

EDIT: I'm using Eclipse IDE if that helps.


Solution

I talked with my instructor today and we fixed the problem by jumping outside of the while loop with a return statement in the catch block, and then initializing s as a new scanner just before entering the loop again. Since the purpose of this snippet is to repeatedly get commands until certain commands that constitute the end of a turn are entered, the while loop is entered every time a command is be entered, and it now works just fine for me.



Answered By - theolaa
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing