NoSuchElementException - completely unable to fix - java.util.scanner

I'm busy developing a relatively simply program.
The program involves the use of a main menu that is created and displayed by a method called: "mainMenu()"; the code for which is contained within in my "Main" class (itself containing the main() method). This method takes input via the scanner and depending upon which option the user inputs, a corresponding method is called.
One of these options is "quit" (option q) which, if the scanner picks up Q as the user input, the mainMenu() method then calls a corresponding method called: "quitProgram().
The quitProgram() method also uses a scanner object (albeit a different one to the one the mainMenu() method uses). It does so becuase, via a prompt, the user is asked: "do you want to quit this program? Yes/No?" and the input to that question is captured by the scanner.
Hopefully you're following all of this ...
It is with respect to the quitProgram() method that I'm having problems. Specifically, a NonSuchElementException is being thrown and if "n" or "no" is inputed. The code excutes perfectly if "yes" or "y" is inputed.
Inputting "no" or "n" should (if I could ever fix this bug), call the mainMenu() method again and take the user back to the main menu except, it doesn't. As intimated, it throws a NoSuchElementException.
I'm hoping that by showing you the code for both methods, you can tell me how to fix the problem.
The mainMenu() method:
public static void mainMenu() {
Scanner sc = new Scanner(System.in); // Create a Scanner object.
boolean userInputCorrect = false; // initialise boolean flag.
String choice; // initialise String for holding user input.
// start do ... while loop
do {
// ask user to input their choice of option:
System.out.println("*********************************************************************************************************" + "\r"
+ "PROGRAMMING ASSIGNMENT:" + "\r"
+ "----------------------" + "\r\n" + "\r\n"
+ "STUDENT ID: 2136272" + "\r"
+ "NAME: William van Zwanenberg" + "\r"
+ "MODULE NAME: LAAM39 - Introduction to Programming" + "\r"
+ "MODULE TUTOR: Dr. Livio Robaldo" + "\r\n" + "\r\n"
+ "DESCRIPTION:" + "\r\n"
+ "------------" + "\r\n"
+ "Program to manage a desk and the items on it as per assignment for LAAM39 - Intro to Programming Module." + "\r\n" + "\r\n"
+ "ASSIGNMENT TITLE:" + "\r\n"
+ "-----------------" + "\r\n"
+ "Implement a Java class \"Desk\" with suitable attributes and methods to put and remove items on the desk " + "\r"
+ "and, optionally, other methods to move the desk, buy&sell the desk, etc. Items are instances of another " + "\r"
+ "Java class \"Item\". By using inheritance among classes, you can then optionally distinguish different " + "\r"
+ "kinds of items (notebooks, pens, pencils, etc.)" + "\r\n" + "\r\n"
+ "**********************************************************************************************************" + "\r\n" + "\r\n"
+ "Please enter the corresponding number for the specific action you'd like the program to perfom." + "\r\n" + "\r\n"
+ "YOUR CHOICE OF OPTIONS ARE:" + "\r\n" + "\r\n"
+ "(1) Create a new desk object;" + "\r\n"
+ "(2) Change the properties of an existing desk object;" + "\r\n"
+ "(3) Add a new stationery item to the desk;" + "\r\n"
+ "(4) Remove an existing stationery item from the desk;" + "\r\n"
+ "(5) Change the properties of an existing stationery item;" + "\r\n"
+ "(6) Move the desk" + "\r\n"
+ "(7) Sell the desk and assign it a new owner." + "\r\n" + "\r\n"
+ "To quit the program, type \"q\"." + "\r\n");
choice = sc.nextLine();
// now instigate switch
switch (choice.toLowerCase()) {
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "q":
case "quit":
case "Quit":
case "QUIT":
// change flag becuase user will have made a valid choice
userInputCorrect = true;
// BREAK OUT OF SWITCH
break;
default:
// clear console
clearConsole();
// include countdown delay. Here the for loop merely interates. Nothing more.
for (double i = 1; i<=1000000; i=i+ .01);
// print out error msg:
System.out.println("\r\n" + "ERROR! " + "\""+ choice +"\"" + " is not a valid choice. Please try again." + "\r\n");
} // end of switch
// end the do .. while loop
} while (!userInputCorrect);
// close the Scanner class as we no longer need it.
sc.close();
// flush the content of the buffer to the output stream
System.out.flush();
/*
* If 'q', Q', 'quit', 'Quit', or 'QUIT' is inputed, then quit the program.
* NB: For some reason (UNKNOWN) despite using the 'toLowerCase()'
* String method, the code does not execute
* correctly if "Q" is entered by the user. Therefore, the
* "||" Comparator has been used alongisde the 'equalsIgnoreCase' method in
* to avoid producing an error and forcing the program to quit. This is
* obviously a workaround.
*/
if (choice.equalsIgnoreCase("Q") || choice.equalsIgnoreCase("QUIT")) {
// call quit program method:
quitProgram();
} else {
clearConsole();
System.out.println("\r\n" + "You selected: " + choice);
// now include switch to pass flow to corresponding classes/methods/ depending on the user's selection.
}
} // end of mainMenu() method.
This is the code for the quitProgram() method:
public static void quitProgram() {
//clear console:
clearConsole();
// create a new scanner:
Scanner scan = new Scanner(System.in);
// ask user if thwy wish to quit:
System.out.println("Do you want to quit this program? Yes/no?");
// assign user input to a new String:
String options = scan.nextLine();
// initialise boolean for use in while loop:
boolean matchFound = false;
String regex = "yes|no|y|n"; // searches for "yes", "no", "y", and "n" - CASE INSENSITIVE.
while (matchFound == false) {
Pattern pt = Pattern.compile(regex , Pattern.CASE_INSENSITIVE);
Matcher mt = pt.matcher(options);
if (mt.find() == true) {
// match found, therefore set the boolean to true:
matchFound = true;
} else {
// print out error msg:
System.out.println("Invalid entry. Please try again. Do you want to quit this program? Yes/no?");
// get next entry:
options = scan.next();
}
} // end while loop.
// NOW ACT DEPENDING ON SPECIFIC CHOICE:
// close the scanner:
scan.close();
// flush the content of the buffer to the output stream
System.out.flush();
if (options.equalsIgnoreCase("yes") || options.equalsIgnoreCase("y")) {
// clear the Console
clearConsole();
// print out goodbye message:
System.out.println("GOODBYE :-) This program will now quit");
// wait a short while ...
for (double i = 1; i<=10000000; i=i+ .01); // include countdown delay. Here, the for loop merely interates. Nothing more.
// clear console again:
clearConsole();
// now definitely quit.
System.exit(0);
} else if(options.equalsIgnoreCase("no") || options.equalsIgnoreCase("n")) {
// clear console:
clearConsole();
// flush the content of the buffer to the output stream
System.out.flush();
// print out take to main menu message:
System.out.println("OK. Returning you to the main menu ...");
// clear console again:
clearConsole();
// wait a short while ...
for (double i = 1; i<=100000; i=i+ .01); // include countdown delay. Here, the for loop merely interates. Nothing more.
// return to the main menu.
mainMenu();
}
} // end of quitProgram() method.

Related

I'm not sure how to carry on after a person selects one question

System.out.println(" ");
System.out.println("I knew something was up driving past that billboard.");
System.out.println(" ");
System.out.println("Something didn’t feel right.");
System.out.println(" ");
System.out.println(sName + " " + "Watch out there's a deer!!!");
System.out.println(" ");
System.out.println("1) Turn to the left ");//Three options to choose from.
System.out.println("2) Turn to the right ");
System.out.println("3) Continue driving forward ");
int iAnswer = 0;// Need to put this above so it'll work.
iAnswer = Integer.parseInt(System.console().readLine()); // Finding when we're getting there
if (iAnswer == 1) {
System.out.println("You skid to the left dramatically, and injure Keith badly.");
if (iAnswer == 2) {
System.out.println("Skid to the right fast avoiding the deer and crash the car into a tree damaging" + " " + sName + ".");
if (iAnswer == 3){
System.out.println("You hit the deer, and die of a fatal accident flipping the car and killing both your friends.");
}
}
}
For example if the person playing chooses 1 as the answer resulting in Keith being injured badly from the car crash I'd like to use this as a disadvantage later for the person playing. How'd I tell the PC to follow that specific path onward from that answer. And how'd I end the game if they chose question 3 resulting in all characters dying.
You can create a boolean variable keithInjured at the beginning of the program, set it to true if the user enters 1, and check its value later in the program when it is relevant.
You can put the different execution path in methods, and call the right method in the if-statements.
Also note that you wrapped the last 2 if-statement (which check if the input was 2 or 3) into the first one. If the first if-statement's condition evaluates to false, the second two will not be checked because they are within the scope of the first one. Close the braces of an if-statement at the end of its code block.
boolean keithInjured = false;
if (iAnswer == 1) {
System.out.println("You skid to the left dramatically, and injure Keith badly.");
keithInjured = true;
path1();
}
if (iAnswer == 2) {
System.out.println("Skid to the right fast avoiding the deer and crash the car into a tree damaging" + " " + sName + ".");
path2();
}
if (iAnswer == 3){
System.out.println("You hit the deer, and die of a fatal accident flipping the car and killing both your friends.");
path3();
}
//later in program
if (keithInjured) {
//do something
}

Function doesn't execute inside loop

I'm making a simple terminal calculator but for some reason a function isn't executing inside a while loop but executes outside the loop.
Given this input: ((1 + 2) + (3 + 4))
It should output:10
But gets stuck in an infinite loop because it doesn't replace the innermost expressions with their result.
The function that doesn't execute is s.replace(basicOp, answer);
Here is a snippet of the problem:
public static function processInput(s:String):String
{
var result:Null<Float> = parseNumber(s);
if (result != null)
{
return Std.string(result);
}
var closeParPos:Int = 0;
var openParPos:Int = 0;
var basicOp:String;
var answer:String = "";
// ERROR HERE
while (Std.string(answer) != s)
{
closeParPos = s.indexOf(")");
openParPos = s.lastIndexOf("(", closeParPos);
basicOp = s.substring(openParPos, closeParPos + 1);
answer = processBasicOp(basicOp);
// This isn't executed
s.replace(basicOp, answer);
trace("Input: " + s + " basicOp: " + basicOp + " Answer: " + answer);
}
return (result == null)? "": Std.string(result);
}
All the code is here just run make test
The input syntax is: ([number] [operator] [number]) or ([operator] [number])
There must be a single space between number and operators.
There shouldn't be any space between numbers and parenthesis
Supported operations:
+ - / *
% (remainder),
div (quotient),
sqr (square),
sqroot (square root),
sin cos tan (in degrees, bugged)
fact (factorial)
It isn't completed yet, there may be other problems, but this problem prevents me from advancing.
Can someone help me find the solution?
Thank you.
I can't actually get this to run, but StringTools.replace() doesn't modify the string in-place.
Try changing s.replace(basicOp, answer); to s = s.replace(basicOp, answer);

Getting Barcode Scanner MT2000 to Move to Next Focus

I am trying to move to the next focus of an application by transmit a TAB or ENTER character to the host from my Motorola MT2070 Barcode Scanner.
I have tried using the SendLabel method as follows
string barcode = "Hello";
int count = 1;
SendBarcode(new LabelData(barcode + "\t" + count.ToString(), Options.BarcodeType));
count++;
}
private bool SendBarcode(LabelData label)
{
RESULTCODE result = RESULTCODE.E_OK;
try
{
result = Program.ScannerServicesClient.SendLabel(label, 10000);
}
catch
{
result = RESULTCODE.E_HOST_NOT_READY;
}
if (result != RESULTCODE.E_OK)
{
MsgBox.Error(listForm, Properties.Resources.StrErrorCouldntSendBarcode);
}
return result == RESULTCODE.E_OK;
}
Unfortunately the "\t" does not translate into an actual TAB keystroke in Keyboard mode.
When scanning in NOTEPAD the 5 spaces of the tab show up, but it doesn't work to move the focus to the next field as hitting TAB does in Excel or other applications.
What should I be transmitting in place of the \t?
Thanks!
I assume this won't work, because it is not a normal/manual input from your keyboard. It is a value passed from a barcode to the text-property of your field. So you have to handle this different.

Swift - Update UITextView with string using IBAction without deleting old string

I am trying to send and update strings inside a UITextView using and IBAction button.
the code below works fine however, every time i push the button the old text is replaced with the new one. What I am trying to do is to always append the text to the exiting one.
Any Idea?
#IBAction func equalPressed(sender: AnyObject) {
var resultString:String = "new string"
textView.text = resultString.stringByAppendingString("= " + resultLabel.text! + ";")
}
You already know how to append strings, but you're doing it two different ways. The stringByAppendingString(_:) method is fine, but Swift's + operator is clearer. I'd rewrite your existing method as follows:
#IBAction func equalPressed(sender: AnyObject) {
let resultString = "new string"
textView.text = resultString + "= " + resultLabel.text! + ";"
}
Then, to append the text rather than replace it, it's a simple change of including the old value in the new one:
textView.text = textView.text + resultString + "= " + resultLabel.text! + ";"
Or, using the += operator (x += y is short for x = x + y):
textView.text += resultString + "= " + resultLabel.text! + ";"

How to go to next line while using a loop to setText in JTextArea?

This is my code
for (int m=0; m < i ; m++){
ta1.setText( s[m].getName().toString() + ", " + s[m].getProgramName().toString() + ", " + s[m].getUni1() + ", " + s[m].getUni2() + ", " + s[m].getUni3() + ", " );
}
It's supposed to print a line from an array of student ( called s) into a JTextArea ( called ta1 ). the problem is that it always only prints the last student in the array.
I need to print each student in a new line. could anyone help me sort it out?
When you set text on an element, the current position in the loop will take over the last one.
Try doing this.
String s = "";
for(int m = 0, m <i; m++){
s += s[m].getName.toString() + ", " + s[m].getprogramName().toString() + "\n;
}
ta1.setText(s);
Create a string and add each entry to it then add new line to end of each entry "\n"
Then do.
ta1.setText(s);
setText overwrites whatever is the current text.
You need append instead; you also need a "\n" at the end of a line.

Resources