import javax.swing.JOptionPane;
public class sam{
public static void main(String[]args){
String a;
String b;
int c;
sam s1 = new sam();
a=s1.getInfo();
c=s1.getBalance();
b=s1.getMenu(a,c);
}
//menu method starts here
public String getMenu (String c, Integer d) {
String[] a;
String[] choices = { "Account Balance", "Deposit", "Withdraw", "User Account", "Exit options"};
String input = (String) JOptionPane.showInputDialog(null, "What would you like to do?",
"ATM menu", JOptionPane.QUESTION_MESSAGE, null,choices,choices[0]);
if ((choices[0] == choices[0])){
JOptionPane.showMessageDialog(null,"Your Account Balance is: "+d,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//the if statement is executing properly
else if ((choices[1] == choices[1])){
String in=JOptionPane.showInputDialog("Deposit: ");
int deposit=Integer.parseInt(in);
int add=d+deposit;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+add,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//but when I chose account balance it displays the if statement not the else-if one
else if ((choices[2] == choices[2])){
String in=JOptionPane.showInputDialog("Withdraw: ");
int withdraw=Integer.parseInt(in);
int sub=d+withdraw;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+sub,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[3] == choices[3])){
JOptionPane.showMessageDialog(null," "+c,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[4] == choices[4])){
JOptionPane.showMessageDialog(null,"The program will be terminated in a few seconds","ATM machine",JOptionPane.INFORMATION_MESSAGE);
}
return input;
}
//I'm quite new to programming, I rushed coded it for finals.
All of your if statements will evaluate to true. I think your intentions were to compare String c with each of the Strings in the choices array.
When comparing Strings always use .equals() not ==.
Example:
if (c.equals(choices[0])) {
// code
} else if (c.equals(choices[1])) {
//code
} else if (c.equals(choices[2])) {
// code
}
Related
I am a beginner and I am creating a game. I am trying to use a variable (userOption) from another procedure (Weapons) in an if statement in the main procedure. The if statement is supposed to say that if userOption is 2 (a wooden stake) and if the Monster is a Werewolf then the wooden stake works and kills the Werewolf. I would like to do this for the other Monsters. Is it possible to do so? If so, how do you do it?
using System;
namespace Halloween
{
class Program
{
static void Weapons()
{
int userOption = 0;
Console.WriteLine("What weapon will you choose?");
Console.WriteLine("1. A silver bullet");
Console.WriteLine("2. A wooden stake");
Console.WriteLine("3. A priest");
Console.WriteLine();
userOption = Convert.ToInt32(Console.ReadLine());
if (userOption == 1)
{
Console.WriteLine("You have chosen a silver bullet as your weapon");
YesOrNo();
}
else if (userOption == 2)
{
Console.WriteLine("You have chosen a wooden stake as your weapon");
YesOrNo();
}
else if (userOption == 3)
{
Console.WriteLine("You have chosen a priest as your weapon");
YesOrNo();
}
else
{
Console.WriteLine("You have chosen not to arm yourself as you did not enter 3, 2 or 1");
YesOrNo();
}
Console.ReadLine();
}
static void YesOrNo()
{
string userChoice = "";
Console.WriteLine("Are you sure? Y or N?");
userChoice = Console.ReadLine();
if (userChoice == "Y")
return;
else if (userChoice == "N")
Weapons();
}
static void Main(string[] args)
{
string userName = "";
Console.WriteLine("Hey stop!");
Console.ReadLine();
Console.WriteLine("What is your name?");
userName = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("There is something lurking in the shadows {0}, you have a choice of three weapons",
userName);
Weapons();
Console.WriteLine("A shape has emerged from the shadow!");
Console.Read();
Console.WriteLine("It is moving towards you. It comes closer and closer until you can tell it is a...");
Console.Read();
Random rnd = new Random();
int monsterNumber = rnd.Next(3);
string[] arrayMonsters = {"Werewolf", "Vampire", "Ghost"};
string Monster = arrayMonsters[monsterNumber];
Console.WriteLine(Monster);
if (Monster == "Werewolf")
(userOption == 2)
Console.WriteLine("You drove the wooden stake through the Werewolf and successfully killed it");
}
}
}
Im having trouble figuring out some compiler errors such as illegal start to expression in my if and else statements and an else without an if.
import java.util.Scanner;
public class A3Q1
{
public static void main(String[]args)
{
System.out.println("Perfect square identifier (Enter -1 to quit program)");
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
String squareNumStr = sc.nextLine(); //taking user input
int squareNum = Integer.parseInt(squareNumStr); // taking string turning it into int
boolean exitCommand = true;
while(exitCommand)
{
if(squareNum >= 0) // will run method if int is a positive
{
perfectSquareIdentifier();
if(return == true) // using boolean return to print
{
System.out.println(squareNum + " is a perfect square.");
}
else if(return == false)
{
System.out.println(squareNum + " is not a perfect square");
}
}
else if(squareNum == -1)
{
exitCommand = false;
System.out.println();
}
}
System.ou.println("End of processing...");
}
public static boolean perfectSquareIdentifier(int squareNum)
{
int squareRoot = Math.sqrt(squareNum); //taking square root of user input
if (squareRoot*squareRoot == squareNum) // testing if the root provided is a root or a number with remainders
{
return true;
}
else
{
return false;
}
}
}
This a menu based program to create a database of people and for performing operations on their name. After compilation, I am able to add a person successfully using the add function of Person class but when I retrieve the list of the added people using list function it shows garbage values instead of showing the entered names. It's the question no. 4(lab 4) in the below give doc.
https://drive.google.com/open?id=18cR9bgPlqM6q-kXBIcxg5Hpj04bkZMnW&authuser=0
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
class Person
{
const char *name;
public:
Person(const char* n)
{
name=n;
}
bool search(const char* substr)
{
const char *str=name;
while(*str!='\0')
{ int count=0;
if(*str==*substr)
{ const char *s=substr;
const char *p=str;
while(*s!='\0')
{
if(*p==*s)
{
count++;
p++;
s++;
}
else
break;
}
}
if(count==strlen(substr))
{
cout<<name<<endl;
return true;
}
str++;
}
return false;
}
void print()
{
cout<<name<<endl;
}
~Person()
{
cout << ":)";
}
friend class People;
};
class People
{
Person** array;
int length;
void prompt()
{
cout << "\n'A'-Add a person\n'L'-List all persons\n'S'-Search\n'Q'-Quit\n";
}
public:
People()
{
array = NULL;
length = 0;
}
void add()
{
string m;
cout << "Enter a Name:\n";
cin >> m;
Person s(m.c_str());
if (array == NULL)
array = (Person**)malloc(sizeof(Person*));
else
{
array=(Person**)realloc(array, length*sizeof(Person*));
}
array[length] =new Person(s.name);
array[length]->print();
++length;
}
void list()
{
cout << "\nThe names of the person in the list are:\n";
for (int i = 0; i <length; i++)
{
array[i]->print();
}
}
void search()
{
string a;
int flag = 0;
cout << "\nEnter a string to be found in the names present in the list:\n";
cin >> a;
cout << "\n The names with entered substring are:\n";
for (int i = 0; i <length; i++)
{
bool state=array[i]->search(a.c_str());
if (state)
flag = -1;
}
if (flag == 0)
cout << "\nNone of the names contains the entered substring!!!\n";
}
void menu()
{
char c = 'Y';
while (c != 'Q')
{
cout << "Choose an option(character):\n";
prompt();
cin>>c;
switch (c)
{
case 'A':add();
cout << "Name entered sucessfully!!!\n";
break;
case 'L':list();
break;
case 'S':search();
break;
case 'Q':c = 'Q';
break;
}
}
}
};
int main()
{
People All;
All.menu();
return 0;
}
I am not able to find any mistake in my implementation of add function. What could be the possible reason for malfunctioning of list function?
tl;dr
You store a pointer to the internal memory of string (m). That string gets destroyed at the end of add() so you have pointer to unallocated memory, which causes undefined behaviour.
possible solutions
Best would be to store a std::string instead of a const char * inside Person.
walkthrough
If you want a more detailed analyses: You store a pointer to a string that goes out of scope.
void add()
{
string m; // string is initialized and allocates memory for its content
cout << "Enter a Name:\n";
cin >> m; // read content
Person s(m.c_str()); // m.c_str() retrieves a pointer to the memory allocated by m
//this pointer is stored inside s
if (array == NULL)
{
array = (Person**)malloc(sizeof(Person*));
}
else
{
array=(Person**)realloc(array, length*sizeof(Person*));
}
array[length] = new Person(s.name); // s.name still points to the memory allocated by m
array[length]->print();
++length;
} //At the end of the function m gets destroyed and deallocates its memory
So after the function exits you still have stored the pointer to m.c_str() inside a persons name. This pointer now points to unallocated memory. This memory now may (or may not) be overwritten at any time. You get undefined behaviour and print garbage.
I am working on a project in which I have an account class that stores balances for different funds. Each account object has 10 funds in which they start at 0 and transactions such as deposit, withdraw, and tranfer can be made. I need to store these accounts in a binary search tree as they are added and I am having issues with my retrieve function. The code is the following:
bool Retrieve(const int & acctNum, Account* acctPtr)
{
if (Search(root, acctPtr, acctNum))
return true;
else
return false;
}
bool Search(Node* temp, Account* acctPtr, int acctNum)
{
if (temp == NULL) {
return false;
}
else if (temp->pAcct->getAcct() == acctNum)
{
acctPtr = temp->pAcct;
return true;
}
else if (acctNum <= temp->pAcct->getAcct())
{
return Search(temp->left, acctPtr, acctNum);
}
else
{
return Search(temp->right, acctPtr, acctNum);
}
}
The problem I am running into is when I deposit into the account and then later retrieve and try to withdraw, it is not giving me the same account. Rather, it just tries to withdraw from an account with all 0 balances. My intention is for the acctPtr to point to the correct account to do the transfer/withdraw/deposit too. Here is how I am calling the retrieve from a different class that is used for completing the transactions:
if (transType == "D")
{
iss >> acctNum >> amt;
fund = parseCommand(acctNum);
acctNum = acctNum.substr(0, acctNum.length() - 1);
Account * d = new Account("name", stoi(acctNum));
if (bST->Retrieve(stoi(acctNum), d))
{
d->deposit(fund, amt);
cout << d->getFundBalance(fund) << endl; //for checking, will remove
}
}
else if (transType == "W")
{
iss >> acctNum >> amt;
fund = parseCommand(acctNum);
acctNum = acctNum.substr(0, acctNum.length() - 1);
Account * wD = new Account("name", stoi(acctNum));
if (bST->Retrieve(stoi(acctNum), wD))
{
wD->withdraw(fund, amt);
cout << wD->getFundBalance(fund) << endl; //for checking, will remove
}
}
The if statements above are just checking the type of transaction at the given time.
In your Search function, you use the argument acctPtr as an output (you assigned a new value to it).
But your pointer is not an output argument.
You should use Account** or Account*&.
And you will have to use the Retrieve method like this :
Account* d = NULL;
if(bST->Retrieve(stoi(acctNum),&d /* or just d if Account*& */))
{ ... }
If you use the Account** version, don't forget to assign the pointer with
*acctPtr = temp->pAcct;
I an odd problem that i cant understand if someone could point me in the right direction it would be greatly appreciated.I create my own linked list variables on the heap but when i go to add another variable to it they all get destroyed and i dont know why.
in my main i set up my variables like this
main.cpp
Book* temp;
temp = bookSetUp();
this goes to a different cpp called functions which sets up the objects like this:
functions.cpp
Book* bookSetUp()
{
//The items that populate the list
Book* a= new Book("A Tale of Two Cities", "Charles Dickens", "1", true);
Book* b= new Book("Lord of the rings", "J.R.R Tolkein", "2", true);
Book* c= new Book("Le Petit Prince", "Antoine de Saint-Exupéry", "3", true);
Book* d= new Book("And Then There Were None", "Agatha Christie", "4", true);
Book* e= new Book("Dream of the Red Chamber","Cao Xueqin","5", true);
Book* f= new Book("The Hobbit","J.R.R Tolkein","6", true);
//sets up the pointers between books
a->setPrev(NULL);
a->setNext(b);
b->setPrev(a);
b->setNext(c);
c->setPrev(b);
c->setNext(d);
d->setPrev(c);
d->setNext(e);
e->setPrev(d);
e->setNext(f);
f->setPrev(e);
f->setNext(NULL);
//sets up a temp pointer to a
Book* temp = a;
//returns the temp pointer to a
return temp;
}
this works perfectly but later on when i go to add to the list again in the main using:
main.cpp
else if(checkRegUser(username, password, regUserList) == true)
{
int choice = 99;
cout << "Welcome Registered user: "<< username << endl;
while(choice != 0)
{
//this is so the print will start everytime as if you run it once print will be at NULL thereafter
Book* print = temp;
choice = options();
if(choice == 1)
{
while(print!=NULL)
{
cout<<"Name: "<<print->getName()<<endl<<"Author: "<<print->getAuthor()<<endl<<"ISBN: "<<print->getISBN()<<endl<<"Availability: "<<print->getAvail()<<endl;
cout<<endl;
print = print->getNext();
}
print = temp;
}
if(choice == 2)
{
search(temp);
}
if(choice == 3)
{
takeOut(temp);
}
if(choice == 4)
{
returnBack(temp);
}
if(choice == 5)
{
append(temp);
}
if(choice == 6)
{
cout<<"Sorry you have the privilege needed to use this function."<<endl;
}
if(choice == 7)
{
choice = 0;
}
}
}
My user defined variables get destroyed. I debugged and they just disappeared i am not sure why!
Just in-case its needed here is my add() function because I feel It could be me missing something small or just making a disastrous mistake. My add function is in the functions.cpp and I know all the links are working as I have everything else running apart from this
functions.cpp
Book* append(Book* tempParam)
{
string title;
string author;
string isbn;
bool avail;
cout<<"What is the book called?"<<endl;
cin.clear();
cin.ignore();
getline(cin, title);
cout<<"Who is the author?"<<endl;
cin.clear();
cin.ignore();
getline(cin, author);
cout<<"What is the ISBN to be?"<<endl;
cin>>isbn;
Book* temp = new Book(title, author, isbn, true);
Book* list = tempParam;int count;
while(list!=NULL)
{
if(list->getNext()==NULL&&list->getName()!=title)
{
list->setNext(temp);
temp->setNext(NULL);
temp->setPrev(list);
cout<<"Your book has been added"<<endl;
cout<<temp->getName()<<temp->getAuthor()<<endl;
}
list = list->getNext();
}
tempParam = list;
return tempParam;
}
My user defined classes are working perfectly its just when I go to add that my list gets destroyed any ideas??
*I think the error is found in this section of the code:
list->setNext(temp);
You are "losing" the books because you didn't save them before you change list->next.*
The answer is incorrect because the conditional statement makes sure that it is the last element of the list. Sorry!