How should I rewrite the code for this program? - if-statement

The function of the program is to let the user know if a number is prime. The code compiles but the string does not print and I cannot type in any user input.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num=0;
int i=2;
System.out.print("Which number would you like to check?");
num = sc.nextInt();
while (i<=num) {
if (i ==num || num==1||num==0) {
System.out.print("Is not prime");
}
else if (num%i==0){
System.out.print("Is prime");
}
else {
++i;
}
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num=0;
int c=0; //A counter to store the number of factors
System.out.print("Which number would you like to check?");
num = sc.nextInt();
for(int i=1;i<=num/2;i++){
if(num % i==0)
c++;
}
if(c==1)
System.out.print("Prime");
else
System.out.print("Not Prime");
}

Related

How can i solve this problem of a Lexical Analyzer that is written in C++?

I want to make a lexical analyzer using c++ that can -
remove single/multiline comments and produce the fresh text
identify keywords
identfy variables
identify special symbols
from a text file as input of the program and finally output all of them in a separate text file as output from the program.
I have already coded the program. But It is unable to identfy the identifiers as variable and removing any commentline from the given text. My code is given below:
#include<bits/stdc++.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
using namespace std;
int isKeyword(char buffer[])
{
char keywords[32][10] =
{
"auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while"
};
int i, flag = 0;
for(i = 0; i < 32; ++i)
{
if(strcmp(keywords[i], buffer) == 0)
{
flag = 1;
break;
}
}
return flag;
}
int main()
{
char ch, buffer[15], special[]=",;\(){}[]'':";
ifstream My_input_file("D:\\input1.txt");
ofstream My_output_file("D:\\output1.txt");
int mark[1000]= {0};
int i,j=0,kc=0,ic=0,sc=0;
vector < string > k;
vector<char >id;
vector<char>sp;
string line;
int flag=1;
if(My_input_file.is_open())
{
while(getline(My_input_file,line))
{
int lenth=line.length(),i;
char* newline = new char[lenth+1];
strcpy(newline,line.c_str());
for(i=0; i<lenth; i++)
{
if(newline[i]=='/'&& newline[i+1]=='/')
break;
if (newline[i]=='/'&& newline[i+1]=='*')
flag=2;
if (newline[i]=='*'&& newline[i+1]=='/')
{flag=1;
i++;}
else if(flag==1)
My_output_file<<newline[i];
}
My_output_file<<"\n";
while(!My_input_file.eof())
{
ch = My_input_file.get();
for(i = 0; i < 12; ++i)
{
if(ch == special[i])
{
int aa=ch;
if(mark[aa]!=1)
{
sp.push_back(ch);
mark[aa]=1;
++sc;
}
}
}
if(isalnum(ch))
{
buffer[j++] = ch;
}
else if((ch == ' ' || ch == '\n') && (j != 0))
{
buffer[j] = '\0';
j = 0;
if(isKeyword(buffer) == 1)
{
k.push_back(buffer);
++kc;
}
else
{
if(buffer[0]>=97 && buffer[0]<=122)
{
if(mark[buffer[0]-'a']!=1)
{
id.push_back(buffer[0]);
++ic;
mark[buffer[0]-'a']=1;
}
}
}
}
}
}
}
My_input_file.close();
My_output_file<<"Keyword List: "<<endl;
for(int f=0; f<kc; ++f)
{
if(f==kc-1)
{
My_output_file<<k[f]<<"\n";
}
else
{
My_output_file<<k[f]<<endl;
}
}
My_output_file<<endl;
My_output_file<<"Variable List: "<<endl;
for(int f=0; f<ic; ++f)
{
if(f==ic-1)
{
My_output_file<<id[f]<<"\n";
}
else
{
My_output_file<<id[f]<<endl;
}
}
My_output_file<<endl;
My_output_file<<"Special Symbol List: "<<endl;
for(int f=0; f<sc; ++f)
{
if(f==sc-1)
{
My_output_file<<sp[f]<<"\n";
}
else
{
My_output_file<<sp[f]<<endl;
}
}
return 0;
}
I am using this text file as input. Input Text File Image
After running this code into codeblock it produce the following output. Output Text File Image
But, i want the output like this: Output Required From the Program
Where i am going wrong? Please help me to sort out.

How to initialize an object once and use it for all test cases

I have a test class where I have all my test cases for my java project, I want to initialize the service class once which creates an array and I want to use the same array for all the other test cases, I have tried to do that but when the first test case is ran an customer is registered and stored in the array I want to use the customer stored in the array and use it for the next test case but it seems that the customer is not in the array for the next test case i.e a new array is being created or I think that junit is running each test case individually
MainTests.java
package tests;
import static org.junit.Assert.*;
import org.junit.*;
import services.BankingServiceImpl;
import dao.BankingSystemArrayImpl;
public class MainTests {
static BankingServiceImpl bankingService;
private static boolean setupIsDone = false;
#BeforeClass
public static void setup() {
bankingService = new BankingServiceImpl();
}
#Test // 1
public void createCustomer() {
String custName = "Rohan";
String HomeAddressCity = "Pune";
String HomeAddressState = "Maharashtra";
int HomeAddressPincode = 411043;
String LocalAddressCity = "Pune";
String LocalAddressState = "Pune";
int LocalAddressPincode = 411043;
int day = 19;
int month = 9;
int year = 1998;
int result = bankingService.acceptCustomerDetails(custName, HomeAddressCity, HomeAddressState,
HomeAddressPincode, LocalAddressCity, LocalAddressState, LocalAddressPincode, day, month, year);
System.out.println(bankingService.getLength());
assertTrue(result > 0);
}
#Test // 2
public void openCustomerAccount() {
System.out.print(bankingService.getLength());
int customerid = 100;
int balance = 100000;
String accountType = "savings";
int result = bankingService.openAccount(customerid, balance, accountType);
assertTrue(result > 0);
}
#Test // 3
public void Balance() {
int customerid = 100;
int accountid = 50;
int pin = 1007;
int result = bankingService.getAccountBalance(customerid, accountid, pin);
assertTrue(result > 0);
}
#Test // 4
public void amt_withdraw() {
int customerid = 100;
int accountid = 50;
int amount = 10000;
int pin = 1007;
int result = bankingService.withdraw(customerid, accountid, amount, pin);
assertEquals(result, 90000);
}
#Test // 5
public void transfer() {
int customerid = 100;
int accountid = 50;
int customerid1 = 101;
int accountid1 = 51;
int amount = 10000;
int pin = 1007;
boolean result = bankingService.fundTransfer(customerid, accountid, customerid1, accountid1, amount, pin);
assertEquals(result, true);
}
#Test // 6
public void amt_deposit() {
int customerid = 100;
int accountid = 50;
int amount = 10000;
int result = bankingService.deposit(customerid, accountid, amount);
assertEquals(result, 90000);
}
/*
* #Test //7 public void cust_details() { int customerid = 100;
* BankingServiceImpl bankingService = new BankingServiceImpl();
*
* int result = bankingService.getCustomerDetails(customerid);
* assertEquals(result, 90000); }
*/
#Test // 10
public void pin_change() {
int customerid = 100;
int accountid = 50;
int o_pin = 1007;
int n_pin = 1122;
boolean result = bankingService.changePin(customerid, accountid, o_pin, n_pin);
assertEquals(result, true);
}
#Test // 11
public void check_change() {
int customerid = 100;
int accountid = 50;
int pin = 1007;
boolean result = bankingService.checkPin(customerid, accountid, pin);
assertEquals(result, true);
}
}
Service Class
package services;
import beans.Account;
import beans.Address;
import beans.Customer;
import beans.MyDate;
import beans.Transaction;
import dao.BankingSystemArrayImpl;
public class BankingServiceImpl {
BankingSystemArrayImpl BankingSystemArray;
public BankingServiceImpl() {
System.out.print("called");
BankingSystemArray = new BankingSystemArrayImpl();
}
/*
* public void transfer(int accountId, int tansferAccountId, double amount)
* { double a = BankingSystemArray.getAccount(accountId).getBalance()
* - amount; System.out.println(a);
* BankingSystemArray.getAccount(accountId).setBalance(a); double b =
* BankingSystemArray.getAccount(accountId).getBalance() + amount;
* BankingSystemArray.getAccount(tansferAccountId).setBalance(b);
*
* }
*/
public int acceptCustomerDetails(String custName, String HomeAddressCity,
String HomeAddressState, int HomeAddressPincode,
String LocalAddressCity, String LocalAddressState,
int LocalAddressPincode, int day, int month, int year) {
if ((day > 0 && day <= 31) && (month >= 1 && month <= 12)
&& (year <= 2015)) {
return BankingSystemArray.insertCustomer(new Customer(
custName, new Address(LocalAddressCity, LocalAddressState,
LocalAddressPincode), new Address(HomeAddressCity,
HomeAddressState, HomeAddressPincode), new MyDate(
day, month, year)));
} else
return 0;
}
public int openAccount(int custId, int balance, String accType) {
int accountId = 0;
if (custId < 99) {
System.out
.println("Invalid customer Id,please enter a valid customer Id");
} else if (!(accType.equalsIgnoreCase("savings")
|| accType.equalsIgnoreCase("current") || accType
.equalsIgnoreCase("salary"))) {
System.out
.println("Invalid account type, please enter a valid account type");
} else if (balance < 0) {
System.out.println("Invalid amount, please amount a valid amount");
}
else {
Customer customer = BankingSystemArray.getCustomer(custId);
if (customer == null) {
System.out.println("Sorry you have not registered");
return 0;
} else {
Account account = new Account(accType, balance);
accountId = BankingSystemArray.insertAccount(account,
custId);
}
}
return accountId;
}
public int getAccountBalance(int custId, int accNo, int pin) {
if (checkPin(custId, accNo, pin)) {
return BankingSystemArray.getAccount(custId, accNo)
.getBalance();
} else {
System.out.println("Invalid pin");
return 0;
}
}
public int withdraw(int custId, int accNo, int amt, int pin) {
int balance = 0;
if (amt < 0) {
System.out.println("Invalid amount, please enter a valid amount");
} else {
Customer customer = BankingSystemArray.getCustomer(custId);
if (customer == null) {
return 0;
} else {
Account account = BankingSystemArray.getAccount(custId,
accNo);
if (account == null) {
System.out.println("Sorry your account does not exist");
} else if (account.getPin()!=pin) {
System.out.println("Invalid pin");
return 0;
} else {
if ((account.getBalance() - amt) > 0) {
account.setBalance(account.getBalance() - amt);
balance = account.getBalance();
}
}
}
}
return balance;
}
public boolean fundTransfer(int custIdFrom, int accNoFrom, int custIdTo,
int accNoTo, int amt, int pin) {
if (withdraw(custIdFrom, accNoFrom, amt, pin) > 0) {
deposit(custIdTo, accNoTo, amt);
return true;
}
return false;
}
public int deposit(int custId, int accNo, int amt) {
if (amt < 0) {
System.out.println("Invalid amount, please enter a valid amount");
} else {
BankingSystemArray.getAccount(custId, accNo).setBalance(
BankingSystemArray.getAccount(custId, accNo)
.getBalance() + amt);
return BankingSystemArray.getAccount(custId, accNo)
.getBalance();
}
return 0;
}
public Customer getCustomerDetails(int custId) {
Customer customer = BankingSystemArray.getCustomer(custId);
if (customer != null) {
return customer;
}
return null;
}
public Account getAccountDetails(int custId, int accNo) {
Account account = BankingSystemArray.getAccount(custId, accNo);
if (account != null) {
return account;
}
return null;
}
public Account[] getAllAccountsDetails(int custId) {
Account[] account = BankingSystemArray.getAccountList(custId);
if (account != null) {
return account;
}
return null;
}
public Transaction[] getAllTransactionDetails(int custId, int accNo) {
// TODO Auto-generated method stub
return null;
}
public int generatePin(int custId, int accNo) {
Account account = BankingSystemArray.getAccount(custId, accNo);
int pin = BankingSystemArray.generateRandomNumber();
account.setPin(pin);
return account.getPin();
}
public boolean changePin(int custId, int accNo, int oldPin, int newPin) {
Account account = BankingSystemArray.getAccount(custId, accNo);
if (account != null) {
if (account.getPin() == oldPin) {
account.setPin(newPin);
return true;
}
}
return false;
}
public boolean checkPin(int custId, int accNo, int pin) {
Account account = BankingSystemArray.getAccount(custId, accNo);
if (account != null) {
if (account.getPin() == pin) {
return true;
}
}
return false;
}
public Customer getLength() {
return BankingSystemArray.getLength();
}
}
To solve your problem, you need first to understand the JUnit behavior.
Methods marked with #BeforeClass and #AfterClass are run only
once, and are the upper and lower bound of all your test methods.
Methods marked with #Before and #After are run immediately
before and after any test method.
Only static members are shared between test cases. So all instance
members are being reset before any test method.
Also note that as a RULE in Unit Testing, all tests (all test methods) MUST be isolated from each other, but it's OK in integration testing.

error in solution of ANTI-BLOT SYSTEM(spoj)

hello we have to convert an expression like "43 + machula0 = 163"
as 43 + 120 = 163.means we have to scan the expression and then find the missing part.my program runs good without putting the while loop but it shows the error when i run it with the loop.
#include<iostream>
#include<cstring>
#include<cctype>
#include<cstdlib>
using namespace std;
void convert(char *a,int size)
{
int i=0;
char c =a[i];
int f1,f2,f3,n1,n2,s=0; //f1,f2,f3 are flags to check machula
f1=0;f2=0;f3=0;n1=0;n2=0;
while(c!='+')//to store no. before plus in n1
{
c=a[i];
if(isalpha(c))//to check whether the character is alphabet or not
{
f1=1;
}
else if(isdigit(c))//to check whether the character is digit
{
int a = c-'0';
n1=n1*10 + a;
}
i++;
}
while(c!='=')//to store no. before plus in n2
{
c=a[i];
if(isalpha(c))
{
f2=1;
}
else if(isdigit(c))
{
int k = c-'0';
n2=n2*10 + k;
}
i++;
}
while(i!=size)//to store no. before plus in s
{
c=a[i];
if(isalpha(c))
{
f3=1;
}
else if(isdigit(c))
{
int h = c-'0';
s=s*10 + h;
}
i++;
}
if(f3==1)
{
s=n1+n2;
cout<<n1<<" + "<<n2<<" = "<<s<<endl;
}
else
{
if(f1==1)
{
n1=s-n2;
cout<<n1<<" + "<<n2<<" = "<<s<<endl;
}
else if(f2==1)
{
n2=s-n1;
cout<<n1<<" + "<<n2<<" = "<<s<<endl;
}
else
{
cout<<n1<<" + "<<n2<<" = "<<s<<endl;
}
}}
int main()
{
int t;
cin>>t;
while(t--)
{
char *a;
a= new char[10000];
cin.getline(a,10000);
int size = strlen(a);
convert(a,size);
delete []a;
}
return 0;
}
On second thought I do have some useful input. If you are typing this in by hand, there is a attendance to type in the input like this:
1
43 + machula0 = 163" as 43 + 120 = 163
and that leads to problems
int main()
{
int t;
cin>>t; // gets up to the end of the number typed.
// It does not get the carriage return from hitting enter to trigger the input.
while(t--)
{
char *a; // Not relevant to the problem, but this is an awesomely bad idea.
// Use a string
a= new char[10000];
cin.getline(a,10000); // returns instantly with an empty string because of the
// left-over enter used above to get the number.
int size = strlen(a);
convert(a,size); // most of convert does not check size, so instantly out of
// array bounds and crash
delete []a;
}
return 0;
}
It will be valid for input like this:
1 43 + machula0 = 163" as 43 + 120 = 163
Better solution:
void convert(string &a)
{
for (char c: a)
{
//parse logic goes here
}
// output logic goes here
}
int main()
{
int t;
cin >> t;
cin.get();
while (t--)
{
string line;
if (getline(cin, line))
{
convert(line);
}
}
return 0;
}
Unfortunately the convert function needs a lot more work. Most obviously the nearly complete lack of testing for the end of the string.

C++ program runs in linux but not windows

I am writing this program for college and keep having problems with it. I wrote in using codeblocks in ubuntu and it runs fine no errors or anything. But when I run it in windows on codeblocks it crashes and I keep getting the same error "terminate called after throwing an instance of 'std::bad_alloc' what<>: std::badalloc' then it stops working.
Any help would be appreciated!
Thankyou
Ron
main.cpp
#include <iostream>
#include "set.h"
using namespace std;
int main()
{
Set Set1;
List List1;
List1.header();
int choice = 0;
int value = 0;
cout<<"Press 1 to use a list or press 2 for a set"<<endl;
cin>>choice;
if(choice == 1) //List
{
while(choice != 4)
{
value = 0;
List1.menu();
cin>>choice;
switch(choice)
{
case 1:cout<<"Please enter value"<<endl;
cin>>value;
List1.set_value(value);
break;
case 2:List1.print_list();
break;
case 3:List1.test_copy_constructor();
break;
}
}
}
else if(choice == 2) //Set
{
while(choice != 4)
{
value = 0;
List1.menu();
cin>>choice;
switch(choice)
{
case 1:cout<<"Please enter value"<<endl;
cin>>value;
Set1.set_value(value);
break;
case 2:Set1.print_list();
break;
case 3:Set1.test_copy_constructor();
break;
}
}
}
else
{
cout<<"Please Enter a valid option"<<endl;
}
return 0;
}
set.cpp
#include "set.h"
#include <iostream>
#include <string>
using namespace std;
//Constructor
List::List()
{
int array_size;
int *array = new int[array_size];
// delete [] array;
}
List List1;
//Print functions
void List::header(void) const
{
cout<<"Program Name: Program 2"<<endl;
cout<<"Program Created: March 20,2014"<<endl;
cout<<"Created by: Ron Miller"<<endl;
cout<<"--------------------------------"<<endl;
cout<<" "<<endl;
}
void List::menu(void) const
{
cout<<" Menu"<<endl;
cout<<"---------------------------------------------------------"<<endl;
cout<<"1. Insert (value to be inserted is entered from keyboard)"<<endl;
cout<<"2. Print List (all values, one per line)"<<endl;
cout<<"3. Test Copy Constructor (pass list by value to a function"<<endl;
cout<<" and from within the function change all values in list"<<endl;
cout<<" to 0, then call Print List before function ends)"<<endl;
cout<<"4. Quit"<<endl;
cout<<"---------------------------------------------------------"<<endl;
}
//Modification Functions
void List::set_value(const int value)
{
if (slot == 0) //If first run set array size
{
array = new int[array_size];
}
if (slot == array_size) //If array needs extended save data in temp array expand original array then copy back to original
{
cout<<"EXPAND ARRAY"<<endl;
temp_array = array;
array_size = array_size + 2;
array = new int[array_size];
array = temp_array;
}
array[slot] = value; //Set current array slot to value
slot = slot+1;
}
void List::print_list(void) const
{
int i = 0;
cout<<"---------------"<<endl;
while(i < slot)
{
cout<<array[i]<<endl;
i = i+1;
}
cout<<"---------------"<<endl;
}
void List::test_copy_constructor(void) const
{
int* test_array;
test_array = array;
int i = 0;
test_array = new int[array_size]; //Copy original array to test_Array
while(i < slot) //Set array to 0
{
test_array[i] = 0;
i = i+1;
}
i = 0;
cout<<"---------------"<<endl;
while(i < slot) //REMOVE THIS ONLY FOR TESTING PURPOSES
{
cout<<test_array[i]<<endl;
i = i+1;
}
i = 0;
cout<<"---------------"<<endl;
List::print_list(); //Print original array
}
void Set::set_value(const int value)
{
array = get_array(); //Use get functions to obtain copies of private data
temp_array = get_temp_array();
array_size = get_array_size();
temp_array_size = get_temp_array_size();
slot = get_slot();
char match;
match = Set::search_array(value);
if(match == 'y')
{
cout<<"Match"<<endl;
}
if(match == 'n')
{
if (slot == 0) //If first run set array size
{
array = new int[array_size];
}
if (slot == array_size) //If array needs extended save data in temp array expand original array then copy back to original
{
cout<<"EXPAND ARRAY"<<endl;
temp_array = array;
array_size = array_size + 2;
array = new int[array_size];
array = temp_array;
}
array[slot] = value; //Set current array slot to value
slot = slot+1;
set_array(array); //Use set values to update private data
set_temp_array(temp_array);
set_array_size(array_size);
set_temp_array_size(temp_array_size);
set_slot(slot);
}
}
char Set::search_array(int value)
{
array = get_array();
array_size = get_array_size();
slot = get_slot();
int array_value;
char match = 'n';
int i =0;
while(i < slot) //Searches array for a match if there is return y otherwise return n
{
if( array[i] == value)
{
match = 'y';
}
else
{
match = 'n';
}
i = i+1;
}
return match;
}
//Set Functions
void List::set_array(int* value)
{
array = value;
}
void List::set_array_size(int value)
{
array_size = value;
}
void List::set_temp_array(int* value)
{
temp_array = value;
}
void List::set_temp_array_size(int value)
{
temp_array_size = value;
}
void List::set_slot(int value)
{
slot = value;
}
//Get Functions
int* List::get_array(void) const
{
return array;
}
int* List::get_temp_array(void) const
{
return temp_array;
}
int List::get_array_size(void) const
{
return array_size;
}
int List::get_temp_array_size(void) const
{
return temp_array_size;
}
int List::get_slot(void) const
{
return slot;
}
set.h
#ifndef set_H_INCLUDED
#define set_H_INCLUDED
class List
{
public:
//Constructor
List();
//Print Functions
void header (void) const;
void menu (void) const;
//Modification Functions
void set_value (const int);
void print_list(void) const;
void test_copy_constructor(void) const;
//Set functions
void set_array( int*);
void set_temp_array(int*);
void set_array_size( int);
void set_temp_array_size(int);
void set_slot(const int);
//Get functions
int* get_array (void) const;
int* get_temp_array (void) const;
int get_array_size (void) const;
int get_temp_array_size (void) const;
int get_slot(void) const;
private:
int array_size;
int *array;
int *temp_array;
int temp_array_size;
int slot = 0;
};
class Set : public List
{
public:
//Modification Functions
void set_value (const int);
char search_array(const int);
private:
int array_size = 2;
int *array;
int *temp_array;
int temp_array_size = 2;
int slot = 0;
};
#endif
List::List()
{
int array_size;
int *array = new int[array_size];
// ...
}
What value is array_size supposed to have? How large an int array is supposed to be allocated?
It seems to me that this local variable declaration is superfluous; remove it, and use the member variable, instead. (You've initialised the member variable to 2 at its point of declaration, using a new C++11 feature which allows you to do so with a variable that is not static const.)
Don't forget to hand back that allocated memory when you're done with it. In general I would propose that you use std::vector for this.

C++ - run-time crashing of linear probing program

I wrote a program in C++ for hashing using linear probing. The code is showing no error at the time of compilation but when I run it, computer shows the notification that the program has stopped working. I am giving the entire code below. Please help me out.
#include<iostream>
#include<vector>
using namespace std;
class Acc
{
public:
int iData;
double dData;
Acc(int id,double dd)
{
iData = id;
dData = dd;
}
void displayAcc()
{
cout<<"iData = "<<iData<<"\n";
cout<<"dData = "<<dData<<"\n";
}
};
class Linear_Hash
{
private:
vector<Acc*> hashArray;
int nElem;
Acc* noElem;
public:
Linear_Hash(int max)
{
nElem = max;
hashArray.resize(nElem);
noElem = new Acc(-1,1.1);
for(int i = 0;i<max;i++)
{
hashArray[i] = NULL;
}
}
int hashfunc(int key)
{
return key%nElem;
}
void insertAcc(int id,double dd)
{
Acc* newacc = new Acc(id,dd);
int hashVal = hashfunc(id);
while(hashArray[hashVal]->iData!=-1&&hashArray[hashVal]!=NULL)
{
hashVal++;
hashVal = hashVal%nElem;
}
hashArray[hashVal] = newacc;
}
Acc* search(int key)
{
int hashVal = key%nElem;
while(hashArray[hashVal]->iData!=key&&hashArray[hashVal]!=NULL)
{
hashVal++;
hashVal = hashVal%nElem;
}
if(hashArray[hashVal]->iData==key)
{
return hashArray[hashVal];
}
else
return NULL;
}
bool deleteAcc(int key)
{
int hashVal = hashfunc(key);
while(hashArray[hashVal]->iData!=key&&hashArray[hashVal]!=NULL)
{
hashVal++;
hashVal = hashVal%nElem;
}
if(hashArray[hashVal]==NULL)
return false;
else
{
Acc* pTemp = hashArray[hashVal];
hashArray[hashVal] = noElem;
delete pTemp;
return true;
}
}
};
int main(void)
{
int key;
char val;
Linear_Hash lh(20);
lh.insertAcc(100,100.1);
lh.insertAcc(204,204.204);
lh.insertAcc(105,105.10);
lh.insertAcc(237,348.23);
lh.insertAcc(209,923.23);
lh.insertAcc(230,230.23);
lh.insertAcc(403,348.34);
lh.insertAcc(405,938.50);
lh.insertAcc(450,348.23);
lh.insertAcc(945,495.409);
while(val!='x')
{
cout<<"Enter the key to be searched\n";
cin>>key;
if(lh.search(key)==NULL)
cout<<key<<" could not be found\n";
else
lh.search(key)->displayAcc();
cout<<"Enter the key to be deleted\n";
cin>>key;
if(lh.deleteAcc(key))
cout<<key<<" has been deleted\n";
else
cout<<"Invalid request\n";
cout<<"Do you want to continue\n";
cin>>val;
}
return 0;
}
I am unable to use the debugger in this case as I don't know where the error is. I have also tried dry-running it on paper but wasn't able to pin point the bug.
Near the top of main you do this:
Linear_Hash lh(20);
lh.insertAcc(100,100.1);
The first line sets up the vector:
for(int i = 0;i<max;i++)
{
hashArray[i] = NULL;
}
So, before the second line you have a vector of NULLs.
The second line then does this:
Acc* newacc = new Acc(id,dd);
int hashVal = hashfunc(id);
while(hashArray[hashVal]->iData ...
So, hashArray contains NULLS, then you try to look at hashArray[hashVal]->iData i.e.
NULL->iData
You should check hashArray[hashVal]!=NULL before you try to do anything with it.