Tried declaring and initializing selection to have another value other than 'Q' and returning that value so that do while loop would keep running. I can't seem to change the value of the selection variable from inside of a function named quit(). the selection variable is defined within the get_selection() function. I am still very new to coding and C++ can somebody help me with this? I don't know how to change the value of selection to keep the do while loop running once someone enters 'q' or 'Q' to quit the loop. The source code is below. This is my first stack overflow question. Please give constructive feedback if i have asked this question in a bad way so that I learn from it and do better next time. Thank you so much for your time and hope you have a blessed day.
#include <iostream>
#include <vector>
using namespace std;
// Function Prototypes
void display_menu();
char get_selection();
void print_numbers(const vector<int> &list);
void add_number(vector<int> &list);
void remove_number(vector<int> &list);
void display_mean(const vector<int> &list);
void smallest_number(const vector<int> &list);
void largest_number(const vector<int> &list);
char quit();
void handle_unknown();
// End of Function Prototypes
void display_menu() {
cout << "-------------------------------------------\n";
cout << "Please select one of the following choices:|\n ";
cout << "P - Print Numbers |\n ";
cout << "A - Add a Number |\n ";
cout << "R - Remove a Number |\n";
cout << " M - Display Mean of the Numbers |\n ";
cout << "S - Display the Smallest Number |\n ";
cout << "L - Display the Largest Number |\n ";
cout << "Q - Quit |\n ";
cout << "-------------------------------------------\n";
cout << "\nEnter Selection Here: ";
}
char get_selection() {
char selection {};
cin >> selection;
return toupper(selection);
}
void print_numbers(const vector<int> &list) {
// if the User selects P it will display the list within brackets
cout << "\n============================================\n";
cout << "\n[ ";
for ( auto index : list) {
cout<< index << " ";
}
cout << "]";
cout << "\n\n============================================\n\n";
}
void add_number(vector<int> &list) {
// if the user selects A it will Add a Number to the list
int number {};
cout << "\n==========================================================\n\n";
cout << "- Please enter a number to be ADDED to the list: ";
cin >> number;
list.push_back(number);
cout << "- The number " << number << " was ADDED to the list\n\n";
cout << "==========================================================\n\n";
}
void remove_number(vector<int> &list) {
// if the user selects R it will REMOVE a Number from the list
char choice {};
cout << "\n- If you select Yes the last number you added to the list will be REMOVED from the list(Y/N): ";
cin >> choice;
if ( (choice == 'Y' || choice == 'y') && list.size() == 0) {
cout << "- Sorry, but there is currently nothing in the list to remove.\n\n";
cout << "==========================================================================================================\n\n";
}
else if (choice == 'Y' || choice == 'y'){
list.pop_back();
cout<< "- The last number you entered was removed from the list\n\n";
cout << "==========================================================================================================\n\n";
}
else if (choice == 'N' || choice == 'n') {
cout << "- The number survived the purge!!!\n\n";
cout << "==========================================================================================================\n\n";
}
else {
cout << "- You did not enter a valid response, no action was taken\n\n";
cout << "==========================================================================================================\n\n";
}
}
void display_mean(const vector<int> &list) {
// if the user selects M it will display the mean of the numbers
cout << "\n===============================================================\n\n";
int sum {}; //all the integers in the list added together
double mean {}; // the sum / list.size()
for ( auto integer : list) {
sum = sum + integer;
}
mean = static_cast<double>(sum) / list.size();
cout << "- The Sum of all the numbers in the list is: " << sum << endl;
cout << "- The Mean of all the numbers in the list is: " << mean << endl;
cout << "\n===============================================================\n";
}
void smallest_number(const vector<int> &list) {
// Displays the smallest number
cout << "\n=========================================================\n\n";
int min = list.at(0);
for ( auto nums : list ) {
if ( nums < min) {
min = nums;
}
}
cout << "- The Min in the list is: " << min << endl;
cout << "\n=========================================================\n\n";
}
void largest_number(const vector<int> &list) {
// Displays the largest number
cout << "\n=========================================================\n\n";
int max = list.at(0);
for ( auto nums : list ) {
if ( nums > max) {
max = nums;
}
}
cout << "- The Max in the list is: " << max << endl;
cout << "\n=========================================================\n\n";
}
char quit() {
// Are you sure you want to quit prompt
char quit_prompt {};
cout << "\n==============================================\n\n";
cout << "Are you sure you want to quit (Y/N)? ";
cin >> quit_prompt;
if ( quit_prompt == 'Y' || quit_prompt == 'y') {
cout << "Have a blessed day!!!" << endl;
cout << "\n==============================================\n\n";
return 'a';
}
else if ( quit_prompt == 'N' || quit_prompt == 'n') {
cout << "Choose a option\n";
cout << "\n==============================================\n\n";
display_menu();
return get_selection();
}
else if ( quit_prompt == 'Q' || quit_prompt == 'q') {
cout << "Have a blessed day!!!\n";
cout << "\n==============================================\n\n";
return 'a';
}
else {
cout << "You entered a invalid response, no action was taken\n";
cout << "\n==============================================\n\n";
display_menu();
return get_selection();
}
}
void handle_unknown() {
cout << "Unknown selection - try again" << endl;
}
int main() {
vector<int> list {1,2,3}; //have to create the list outside of the loop otherwise the loop will
reset the list every single time the loop resets (lesson learned)
// user input a character that will get saved to this selection variable
char selection {};
// run this loop unless the user inputs 'Q' or 'q'
do {
// tells the user to enter a valid choice if they don't
display_menu();
selection = get_selection();
switch (selection) {
case 'P':
print_numbers(list);
break;
case 'A':
add_number(list);
break;
case 'R':
remove_number(list);
break;
case 'M':
display_mean(list);
break;
case 'L':
largest_number(list);
break;
case 'S':
smallest_number(list);
break;
case 'Q':
quit();
break;
default:
handle_unknown();
}
} while ( selection != 'Q' ); // using the && logical statement because of the != comparison.
return 0;
}
You return a value from the quit function, but you don't save it or act upon it in the main function.
You should probably not return a value from the quit function, and neither should it display the menu or get the selection, as it's done in the main function. Instead I would suggest something like
void quit() {
// Are you sure you want to quit prompt
char quit_prompt {};
cout << "\n==============================================\n\n";
cout << "Are you sure you want to quit (Y/N)? ";
cin >> quit_prompt;
if ( quit_prompt == 'Y' || quit_prompt == 'y' ||
quit_prompt == 'Q' || quit_prompt == 'q') {
cout << "Have a blessed day!!!" << endl;
cout << "\n==============================================\n\n";
exit(0); // Exit the program
}
else if ( quit_prompt == 'N' || quit_prompt == 'n') {
// Do nothing
}
else {
cout << "You entered a invalid response, no action was taken\n";
cout << "\n==============================================\n\n";
}
}
Related
i am making a word guessing game in c++ (im new at programming btw) im just gonna ask how can i make the "already-answered" answers as wrong and cant get points from the same word again? here's my current code...
#include <iostream>
#include <string>
using namespace std;
int main()
{
int firstQPoint, secondQPoint, thirdQPoint, mane;
char yourChoice, levelChoice, goBack;
string yourFirstAnswer, yourSecondAnswer, yourThirdAnswer;
gameMenu:
cout << "\t GUESS THE WORD GAME";
cout << "\t\n\n MADE BY GROUP FIVE";
cout << "\t\t\n\n 1. PLAY | ENTER \"1\" TO PLAY ";
cout << "\t\t\n\n 2. QUIT | ENTER \"2\" TO QUIT ";
cout << "\t\t\n\n 3. RULES | ENTER \"3\" TO SEE THE RULES";
cout << "\t\t\n\n What Do You Want To Do : ";
cin >> yourChoice;
if (yourChoice == '1') {
cout << "\t GUESS THE WORD GAME";
cout << "\t\n\n MADE BY GROUP FIVE";
selectALevel:
cout << "\t\n\n OKAY, CHOOSE A LEVEL (1-3) : ";
cin >> levelChoice;
switch (levelChoice) {
case ('1'):
cout << "\t GUESS THE WORD GAME";
cout << "\t\n\n MADE BY GROUP FIVE";
cout << "\t\t\n\nGIVE 3 BODY PARTS THAT STARTS WITH LETTER \"T\"";
cout << "1 : ";
cin >> yourFirstAnswer;
if (yourFirstAnswer == "TOE", "TONGUE", "TOOTH") {
cout << "\n\n\t\tNICE, YOU GOT A POINT!";
firstQPoint = 1 + 0;
}
cout << "2 : ";
cin >> yourSecondAnswer;
if (yourSecondAnswer == "TOE", "TONGUE", "TOOTH") {
cout << "\n\n\t\tNICE, YOU GOT A POINT!";
secondQPoint = 1 + firstQPoint;
}
cout << "3 : ";
cin >> yourThirdAnswer;
if (yourThirdAnswer == "TOE", "TONGUE", "TOOTH") {
cout << "\n\n\t\tNICE, YOU GOT A POINT!";
thirdQPoint = 1 + secondQPoint;
}
break;
case ('2'):
break;
case ('3'):
break;
default:
goto selectALevel;
}
}
else if (yourChoice == '3') {
do {
cout << "\t GUESS THE WORD RULES";
cout << "\t\t\n\n1. ONLY USE UPPERCASE LETTERS";
cout << "\t\t\n\n1. ONLY USE SINGULAR WORDS";
cout << "\t\t\n\n ENTER \"1\" TO GO BACK : ";
cin >> goBack;
if (goBack == '1') {
goto gameMenu;
}
} while (goBack != '1');
}
else if (yourChoice == '2') {
cout << "\t\t\n\n Okay, Goodbye!";
}
return 0;
}
i tried the longer way, where i will manually code it like this
#include <iostream>
using namespace std;
int main()
{
int number, again;
cout << "give 2 number";
cin >> number;
cout << "again :";
cin >> again;
if (number == 1 && again == 2) {
cout << "correct";
else if (number == 2 && again == 1)
{
cout << "correct";
}
}
}
but it's very hard since im working with too many combinations! thanks in advance for answering!
Inside each switch case you can make a loop to repeat the question if the word is wrong.
At the beginning of the switch (before the loop) you can create an empty list where you will store every answer they give.
In the end you only need to make a function that goes through that same list and checks if a word is inside it or not.
I am a beginner and still learning how to use a switch statement. My professor asked us to make a linked list using a switch statement. I don't really know why the switch statement is not working as intended to be. Hoping someone can help me.
OUTPUT
The output of the program should look like this
Menu
[1] Inserting value in the link
[2] Deleting value in the link
[3] Exit
Enter your choice: (Input)
Inserting/Deleting a value at
[a] Beginning
[b] Middle
[c] End
[d] Exit
Enter your choice: (Input)
Input the value to be inserted/deleted: (Input)
The values in the link are: (Output)
CODE
Here is the code that I'm working with
#include <iostream>
#include <malloc.h>
#include <conio.h>
#define getch() _getch()
using namespace std;
struct dlinklist
{
struct dlinklist* left;
int data;
struct dlinklist* right;
};
typedef struct dlinklist node;
node* start = NULL;
node* getnode()
{
node* newnode;
newnode = (node*)malloc(sizeof(node));
cout << "\n Input the value to be inserted: ";
cin >> newnode->data;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
int menu()
{
char ah;
int ch;
cout << "\n----------------------------------";
cout << "\nMenu";
cout << "\n----------------------------------";
cout << "\n[1] Inserting value in the link";
cout << "\n[2] Deleting value in the link";
cout << "\n[3] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ch;
if (ch == 1)
{
cout << "\n----------------------------------";
cout << "\n Inserting a value at:";
cout << "\n[a] The Beginning of the list";
cout << "\n[b] The middle of the list";
cout << "\n[c] The end of the list";
cout << "\n[d] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ah;
}
else if (ch == 2)
{
cout << "\n----------------------------------";
cout << "\n Deleting a value at:";
cout << "\n[a] The Beginning of the list";
cout << "\n[b] The middle of the list";
cout << "\n[c] The end of the list";
cout << "\n[d] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ah;
}
else if (ch == 3)
{
exit(0);
}
}
void insert_beg()
{
//code
}
void insert_end()
{
//code
}
void insert_mid()
{
//code
}
void delete_beg()
{
//code
}
void delete_end()
{
//code
}
void delete_mid()
{
//code
}
void main(void)
{
int ch = menu();
char ah;
while(1)
{
ah = menu();
switch(ah)
{
case 'A': case 'a':
if (ch == 1)
{
insert_beg();
break;
}
else
{
delete_beg();
break;
}
case 'B': case 'b':
if (ch == 1)
{
insert_mid();
break;
}
else
{
delete_mid();
break;
}
case 'C': case 'c':
if (ch == 1)
{
insert_end();
break;
}
else
{
delete_end();
break;
}
case 'D': case 'd':
exit(0);
}
}
return;
}
menu does not return any value.
You probably want to do this:
int menu()
{
char ah;
int ch;
cout << "\n----------------------------------";
cout << "\nMenu";
cout << "\n----------------------------------";
cout << "\n[1] Inserting value in the link";
cout << "\n[2] Deleting value in the link";
cout << "\n[3] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ch;
if (ch == 1)
{
cout << "\n----------------------------------";
cout << "\n Inserting a value at:";
cout << "\n[a] The Beginning of the list";
cout << "\n[b] The middle of the list";
cout << "\n[c] The end of the list";
cout << "\n[d] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ah;
return ah; // return statement
}
else if (ch == 2)
{
cout << "\n----------------------------------";
cout << "\n Deleting a value at:";
cout << "\n[a] The Beginning of the list";
cout << "\n[b] The middle of the list";
cout << "\n[c] The end of the list";
cout << "\n[d] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ah;
return ah; // return statement
}
else if (ch == 3)
{
// exit(0); don't write this here, call the exit inside main()
return 3; // 3 or anything, you can return other values if you want
}
}
And in main:
int ch = menu();
if (ch == 3) exit(0);
Don't forget about return statements when writing functions.
Important note: Do not use ambiguous names for variables/functions/classes etc. For example, what does ah or ch really mean? How people reading your cryptic code are supposed to know that? Always try to use descriptive names.
This is my first stack overflow question, so please bear with me if I'm not descriptive. My assignment is to create a very simple dice program that's based on a point system, e.g. if you land on a specific number from 1-12, you either win a point, or lose. That's basically all it is. My problem is that, I'm supposed to put a validate function just in case the user put in the wrong input. I made the program to run only if the user input 'y' or 'n', and if not, it will prompt the user to to put the correct response.
class Game
{
private:
int die1;
int die2;
int dice;
int totalPoints;
int totalRolls;
char ch;
void prompt();
void display();
void validate();
void rolls();
public:
void driver();
Game();
};
int main()
{
Game dcObj;
dcObj.driver();
cout << "\n\n\n\n\n\n";
return 0;
}
Game::Game()
{
totalPoints = 0;
totalRolls = 0;
srand(time(NULL));
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
dice = die1 + die2;
}
void Game::driver()
{
prompt();
display();
}
void Game::display()
{
cout << "\n\nYou rolled the dice " << totalRolls << " times.";
cout << "\nYou won " << totalPoints << " points.";
if (totalPoints <= 0)
{
cout << "\n\nBetter luck next time!";
}
else
cout << "Not bad!";
}
void Game::prompt()
{
cout << "\nWelcome To My Game of Absolute Chance!";
cout << "\n\nDo you want to roll? (y = yes, n = no) ";
cin >> ch;
validate();
}
void Game::validate()
{
while (ch != 'n' || ch != 'y')
{
fseek(stdin, 0, SEEK_END);
cin.clear();
cout << "Invalid response. Please input (y = yes, n = no) ";
cin >> ch;
}
}
void Game::rolls()
{
while (ch == 'y')
{
switch(dice)
{
case 2: cout << "Sorry, you rolled a " << dice << ", you lost.";
totalPoints--;
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 3: cout << "Sorry, you rolled a " << dice << ", you lost.";
totalPoints--;
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 4: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 5: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 6: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 7: cout << "Congratulations! You rolled a " << dice << ", you win!";
totalPoints++;
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 8: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 9: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 10: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 11: cout << "Congratulations! You rolled a " << dice << ", you win!";
totalPoints++;
totalRolls++;
break;
case 12: cout << "Sorry, you rolled a << " << dice << ", you lose.";
totalPoints--;
totalRolls++;
break;
}
}
if (ch == 'n')
{
display();
}
}
My issue is that, regardless if there's good input or not, that while loop always runs. Putting 'y' or 'n' will still make it run. I've attempted about almost everything. Any help will be great!
I think the problem is that you used "||" instead "&&" "||" means "or" and"&&" means "and"
I believe the issue lies in your validation function:
void Game::validate()
{
# you have a condition to start the while loop but not end it
while (ch != 'n' || ch != 'y') #using || will cause this to loop infinitely
#as while loop continues until conditions are met
#using && is more appropriate
#as it will end if one of the condition is satisfied
{
fseek(stdin, 0, SEEK_END);
cin.clear();
cout << "Invalid response. Please input (y = yes, n = no) ";
cin >> ch;
}
}
My preference is to accept the correct input and deny anything else because it is much more simpler. IMO, I would use if else for a simpler program.
I assume the ch you declared is a char instead of string as your input is enclosed with '.
void validate() {
if(ch == 'y' && ch == 'n')
{
cout << "game start"; #add on call game function
}
else
cout << "Invalid response. Please input (y = yes, n = no) ";
cin >> ch;
};
or, to follow how u like it:
void validate() {
if(ch != 'y' && ch != 'n')
{
cout << "Invalid response. Please input (y = yes, n = no) ";
cin >> ch;
}
else
cout << "game start"; #add on call game function
};
I'm still working on this project and I have most of my problems fixed.
The problem shows itself while using selection B, but lies in option A and sending the array to the .txt file. There are a lot of extra numbers being added to the .txt file. When I cout, it displays the numbers in the array like it should, but in the text file it looks like this
Anthony201910181114-8589934604445358131768008182078541176802418196927161130726102120444535893
everything before the - is correct, but all of these numbers after need to go.
Why is this happening and how can I fix this?
Thank you.
int main()
{
int Stats[6];
char Selection;
string Character1;
int i;
char keep;
do
{
cout << "Hello, welcome to my character generator. Please select an option" << endl;// Menu Options
cout << "A: Create Character Name and generate stats" << endl;
cout << "B: Display Name and Stats" << endl;
cout << "C: Quit" << endl;
cin >> Selection; // Menu Selection
cout << endl;
if ( (Selection == 'a') || (Selection == 'A') )// if user selects a, this happens
{
cout << "Welcome, Before you can start your adventures you must name your character." << endl;
do
{
cout << "Please enter your a name." << endl;// prompts user to enter a name for their Caracter
cin >> Character1;
cout << "Thank you now lets generate your stats." << endl;
for (i=0; i<6;i++)// I Want this to run the function GenerateScore() 6 times and input each result into the next element of Stats[6]
{
Stats[i]=GenerateScore();
}
for(i=0;i<6;i++)// displays your scores to the player.
{
cout << Stats[i]<< endl;
}
cout << "would you like to keep this name and these Stats?"<< endl;
cout << "Y/N" << endl;
cin >> keep;
break;
}
while ( (keep=='n') || (keep=='N') );
ofstream savecharinfo("charactersave.txt");// saves the Name and the filled array Stats[6] to the charactersave.txt file
if(savecharinfo.is_open())
{
savecharinfo << Character1;
for(int i = 0; i<6; i++)
{
savecharinfo << Stats[i];
}
}
else cout << "File could not be opened." << endl;
}
else if ( (Selection =='b') || (Selection == 'B') )
{
cout << " Welcome back, here are is your character." << endl;
ifstream displaycharacter("charactersave.txt");
if(displaycharacter.is_open())
{
while ( getline (displaycharacter,Character1) )
{
cout << Character1 << endl;
}
displaycharacter.close();
}
else cout << "File could not be opened";
}
else
break;
}
while ( (Selection != 'c') || (Selection == 'C') ); // ends the program is c or C is entered.
return 0;
}
int GenerateScore()
{
int roll1 = rand()%6+2;
int roll2 = rand()%6+2;
int roll3 = rand()%6+2;
int sum;
sum=roll1+roll2+roll3;
return sum;
}
Like was mentioned in the comments:
while ( (keep='n') || ('N') );
should (at least) be changed to
while ( (keep == 'n') || (keep == 'N') );
Also, this loop:
for(int i = 0; Stats[i]; i++)
Will only terminate when Stats[i] evaluates to false, which will only happen when Stats[i] == 0. This loop is causing the extra chars in the file: the code keeps accessing out of bounds array elements until randomly the out of bounds element == 0. You probably want for(int i = 0; i < 6; i++)
when press "1" to start the game a error message comes up first instead of playing the game and then I have to enter "1" 3 times before the game starts and also the quit game option only works when you select "2" first if its not selected first it just comes up as a error message I cant see why it does this can anyone help me please ?
#include "Questions.h"
#include <iostream>
using namespace std;
const int MAXITEMS = 10;
int main ()
{
string question[MAXITEMS] = {"How man cards in a suit",
"How_many_suits_are_there_in_a_standard_pack_of_card",
"How_many_kings_are_in_a_standard_pack_of_cards"};
string answers[MAXITEMS] = {"4", "5", "6"};
int userInput = 0;
int tries = 0;
bool isGameOver = false;
cout << "select 1 to start game" << endl; //gives option to start and quit game
cout << "select 2 to quit game" << endl;
cin >> userInput;
if (userInput == 2)
{
isGameOver = true;
return 0;
};
// when game starts gives option to select question and shows all questions
do
{
if (userInput != 1||2)
{
cout << " Your input is not valid! please try again:" << endl;
// try switch cases for the different outcomes
cout << "select 1 to start game" << endl;
cout << "select 2 to quit game" << endl;
cin >> userInput;
while (!(cin >> userInput))
{
cin.clear(); // clear the error flags
cin.ignore(INT_MAX, '\n'); // discard the row
cout << "Your input is not valid! please try again: ";
cout << "select 1 to start game" << endl;
cout << "select 2 to quit game" << endl;
}
cout << userInput << endl;
}
// reprisent all characters as number to stop while roblem
if(userInput == 1)
{
do
{
cout << "select question" << endl;
for(int i = 0; i != MAXITEMS; i++)
{
cout << i << " " << question[i] << endl;
}
int selectQestion;
cin >> selectQestion;
if(selectQestion == 0||1||2 && tries != 2)
{
cout << "Enter your answer" << endl;
string userAnswer;
cin >> userAnswer;
while (!(cin >> userAnswer))
{
cin.clear(); // clear the error flags
cin.ignore(INT_MAX, '\n');
// discard the row
cout << "Your input is not valid!
please try again: ";
}
if (userAnswer == answers[0])
{
cout << "Correct answer" << endl;
}
else{
cout << "incorrect try again" << endl;
tries++;
cin >> userAnswer;
if (userAnswer == answers[0])
{
cout << "Correct answer" << endl;
}
else
cout << "Incorrect" << endl;
}
}
if (selectQestion == 0 ||1 ||2 && tries == 2)
{
cout << "you can no longer answer this question" << endl;
cout << "try another question" << endl;
}
}
while(userInput == 1);
}
}
while(isGameOver == false);
}
// add stuct or class to handle questions,
if (userInput != 1||2) doesn't do what you think. With the proper paretheses inserted, it is
if ((userInput != 1) || 2)
and 2 is nonzero, hence the condition is always true.
You want
if (userInput != 1 && userInput != 2)
The problem lies here:
if (UserInput!=1||2)
In this line, there are two conditions:
UserInput!=1 , 2
Here , whether user input is 1/2, the second condition 2 is always evaluated as true, which runs the if block
So change it to
if (UserInput!=1 && UserInput!=2)