I'm not sure how to carry on after a person selects one question - repl.it

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
}

Related

NoSuchElementException - completely unable to fix

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.

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.

Controling do while loop with string

Hi folks this is my question for example i have 3 articles and user can chose any one of them or all of them. In the beginning i ask a user, "do you want to choose some articles?" and if he types yes than we start a while or do while loop that adds prices of all chosen articles and adds them to the total value,
for example article one price is 20 and article 3 price is 40 it should write you have chosen articles one and article three and total price is 60. And when user ends with his choosing he types no and the loop ends.
The real question is my do while loop is always endless i don't know how to stop the loop with a String. This my 10th version of code, i tried everything but really can't solve this problem.
public static void main(String[] args) {
Scanner tastatura = new Scanner(System.in);
System.out.println("Artikal 1\nArtikal 2\nArtikal 3");
System.out.println("Do you want to chose a new article");
String choiseString = tastatura.nextLine();
do {
System.out.println("Chose article ");
int choise = tastatura.nextInt();
switch (choise) {
case 1:
System.out.println("Artikal 1 ");
int price = 10;
break;
case 2:
System.out.println("Artikal 2 ");
price= 20;
break;
case 3:
System.out.println("Artikal 3");
price = 30;
break;
}
} while (choiseString.equalsIgnoreCase("yes") );
}
I believe your issue is that you never give the opportunity for the user to change the value of choiseString.
You allow the user to set the value before the loop begins, but once inside the loop it doesn't change.
Your while loop could instead do something like:
do {
System.out.println("Do you wish to continue?");
choiseString = tastatura.nextLine();
System.out.println("Chose article ");
int choise = tastatura.nextInt();
//rest of your logic here
} while (choiseString.equalsIgnoreCase("yes") );
In this case it would then ask for 1 more choice and then exit the loop (although I haven't tested this code).
I recommend to use a boolean.
This way you will only need to check for true or false, or 1/0.
But the important part is to in some point inside the loop, set that variable to true or false, because if you don't do that, the loop will be an infinite loop.
Once you set the variable to false or true in some point inside the loop, everything will goes fine ;)
I hope this helps

Code Outputs mulitple times instead of just once (Unity C#)

Ok I am using Unity C# (MonoDevelop) and I am learning how to pull component variables from other components. Now I understand how to do that, but I am wondering why when I start the game and press the "F" key it prints "Hello I am a cube" and subtracts 1 from CubeTalkPoints at least 3-5 times. I want it to run the code once per key press.
void Update () {
if(Input.GetKey(KeyCode.F))
C_Talk(0);
}
void C_Talk(int SpellID = 0, int TalkPoint = 1)
{
CubeData CubeSub = GetComponent<CubeData>();
if (CubeSub.CubeTalkPoints >= TalkPoint)
{
CubeSub.CubeTalkPoints -= TalkPoint;
Debug.Log("Hello I am a Cube!");
}
}
Use GetKeyDown() instead of GetKey(). GetKeyDown() will only be true the first frame the button is down. GetKey() will be true every frame as long as the button is held down.

Can I jump from one case to another in a switch statements?

For switch statements, is it possible to change the value of the switch inside the switch statement so that it can jump around to different cases?
Ex:
int w = 0;
switch(w)
{
case 1:
doSomething();
w = 3;
case 2:
doSomething();
break;
case 3:
doSomething();
break;
}
Basically what I'm asking is, if I do not place a break statement for a case and I change the value of the switch in the same case, will the code execute both cases?
Yes you can change the value inside switch but it will not execute case for new value until you break in the case where you changed the value.
In your case it will not go in any case as there is no case for 0. But if you change to w = 1 then it will go for case 1 and then for case 2 as you do not have break; but it will not go for case 3.
No, it will not change and will not execute new case statement.
Remember that, once appropriate match is found with the case statement corresponding to a value inside the switch statement, that particular case is executed and once that is executed ( if break is provided after each case to prevent falling through all cases) , then the control returns to the end of switch statement.
Sample Code :
public class A {
public static void main(String [] args) {
int i=1;
switch(i) {
case 1 :
System.out.println("Case 1");
i = 2;
break;
case 2 :
System.out.println("Changed to Case 2");
break;
default:
System.out.println("Default");
break;
}
System.out.println("Final value of i " + i);
}
}
Output :
Case 1
Final value of i 2
Note : Inserting proper breakpoints, try to debug. You will come to know yourself, what exactly is happening.
If we do not give break after each case then Java will start executing the statement from matching case and keep on executing statements for following cases as well, until either a break statement is found or switch statements end is encountered.
If case 1 happens to execute, it's just a fall through to the case 2. And since there is a break in case 2, further fall through doesn't happen. It doesn't jump to case 3 because of the statement w = 3 ; in case 1.
No the switch's case will not change when changing the value in a particular case it checks only once
let a = 1
switch (a) {
case 1:
console.log("Hello from 1")//only this will be printed
a = 2//value of a is changed
break
case 2:
console.log("hello from 2")//this will not execute
a = 3
break
case 3:
console.log("hello from 3")//this will not execute
a = 4
break
case 4:
console.log("hello from 4")//this will not execute
break
default:
console.log("default")
}
console.log(a)//value will be 2

Resources