How to continue the loop even it catches error ArrayIndexOutOfBounds? - arrays

If top==size, it catches an error and displays message Stack is full without stopping the loop .how to do that? But my code below will not stop
here is my code...
while(ask==true){
try{
String input=JOptionPane.showInputDialog("1.Push? Just type yes 2. Pop? just type no");
if(input.equals("yes")){
String element=JOptionPane.showInputDialog("Enter Element");
int num=Integer.parseInt(element);
top++;
arr[top]=num;
System.out.println("Insertion was successful:"+" "+arr[top]);
// isFull();
}else if(input.equals("no")){
pop();
}if(input.equals("exit")){
getStack();
top();
ask=false;
}
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("full");
}
}

while(ask==true) {
try {
String input=JOptionPane.showInputDialog("1.Push? Just type yes 2. Pop? just type no");
if (input.equals("yes")){
String element=JOptionPane.showInputDialog("Enter Element");
int num=Integer.parseInt(element);
top++;
if (top == size) throw new ArrayIndexOutOfBoundsException(); //solution
arr[top]=num;
System.out.println("Insertion was successful:"+" "+arr[top]);
// isFull();
} else if (input.equals("no")){
pop();
} if (input.equals("exit")){
getStack();
top();
ask=false;
}
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("full");
}

Related

Array values are getting replaced by the last value being added in the array

I am writing a basic c program where two people can interact with each other(send messages, read the messages sent by the other person etc.). I am using stacks to store the messages sent. But whenever I am trying to store multiple messages in the array, the previous messages are getting replaced by the last message stored. I am storing the messages sent by the first person in the array arrayMsgs2 and vice versa.
So first I select the first person and send messages to the second person then I switch to the second person to check if the messages from the first person were received. But when I select the unreadMessages2() function (which I literally hard coded to check for the error), we get that all the previous messages have been replaced by the latest message.
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_SIZE 100
int top = -1;
int top2 = -1;
int readMsg1=0;
int readMsg2=0;
char** arrayMsgs1;
char** arrayMsgs2;
void push1(char* message);
void push2(char* message);
char* allocateMemoryForMessage(char* msg)
{
return (char*)malloc(strlen(msg)*sizeof(char));
}
//...................................................................................................................................for the first person
void sendMessageTo2(char* msg)
{
arrayMsgs2[++top2] = allocateMemoryForMessage(msg);
arrayMsgs2[top2] = msg;
printf("\nStoring message in the index %d: %s",top2,arrayMsgs2[top2]);
//push1(newMessage);
return;
}
void push1(char* message)
{
arrayMsgs2[++top2] = message;
return;
}
void displayAllMessages1()
{
if(top==-1) //..........................Checking if there are no messages
{
printf("\nNo messages to display");
return;
}
int i;
for (i=0;i<=top;i++) {
printf("\n%s", arrayMsgs1[i]);
}
readMsg1=top+1; //........................To ensure all the messages are marked read.
return;
}
void unreadMessages1()
{
if(readMsg1>top)
{
printf("\nNo messages unread");
return;
}
printf("\n%d Unread Messages",top - readMsg1 + 1);
while(readMsg1<=top)
{
printf("\n%s",arrayMsgs1[readMsg1]);
readMsg1++;
}
}
//...............................................................................................................................For the second person
void sendMessageTo1(char* msg)
{
char* newMessage = allocateMemoryForMessage(msg);
newMessage = msg;
push2(newMessage);
}
void push2(char* message)
{
arrayMsgs1[++top] = message;
return;
}
void displayAllMessages2()
{
if(top2==-1) //.....................Checking if there are no messages
{
printf("\nNo messages to display");
return;
}
int i;
for (i=0;i<=top2;i++) {
printf("\n%s", arrayMsgs2[i]);
}
readMsg2=top+1; //........................To ensure all the messages are marked read.
return;
}
void unreadMessages2()
{
if(readMsg2>top2)
{
printf("\nNo messages unread");
return;
}
printf("\n%d Unread Message(s)",top2 - readMsg2 + 1);
printf("\n%s",arrayMsgs2[0]);
printf("\n%s",arrayMsgs2[1]);
}
int main()
{
arrayMsgs1 = (char**)malloc(100*sizeof(char*)); //................................allocating memory for the stack of messages
arrayMsgs2 = (char**)malloc(100*sizeof(char*)); //................................allocating memory for the stack of messages
int person;
printf("\nWhich person are you?(1 or 2) ");
scanf("%d",&person);
int choice;
do {
printf("\n\n-----Menu-----");
printf("\n1:Send a message");
printf("\n2:Read unread messages");
printf("\n3:Display all the messages recieved");
printf("\n4:Switch Person");
printf("\n5:Exit");
printf("\n\nEnter your choice\n");
scanf("\n%d", &choice);
switch (choice)
{
case 1:printf("\nEnter the message to send: \n");
char messageToBeSent[100];
scanf(" %[^\n]%*c", messageToBeSent);
if(person==1)
sendMessageTo2(messageToBeSent);
else
sendMessageTo1(messageToBeSent);
break;
case 2: if(person==1)
unreadMessages1();
else
unreadMessages2();
break;
case 3: if(person==1)
displayAllMessages1();
else
displayAllMessages2();
break;
case 4: if(person==1)
{
printf("\nSwitching to the second person.");
person = 2;
}
else
{
printf("\nSwitching to the first person.");
person = 1;
}
break;
case 5:printf("\nExited ");
break;
default:printf("\nPlease enter a value between 1 and 4");
break;
}
} while (choice != 5);
}

What do I do with the error in implementing the stack?

#include <stdio.h>
#define stack 100
void push(int x);
int st[stack];
int top = -1;
int IsEmpty()
{
if (top < 0)
return false;
else
return true;
}
int Isfull()
{
if (top >= stack - 1)
return true;
else
return false;
}
void push(int x)
{
if (Isfull() == true)
printf("stack is full");
else
st[++top]=x;
}
int pop() {
if (IsEmpty() == true)
printf("stack is empty.");
else
return stack[top--];/// There is an error in this part. (expression must have pointer-to-object type)
}
int main()
{
push(3);
}
int pop() {
if (IsEmpty() == true)
printf("stack is empty.");
else
return stack[top--];There is an error in this part. (expression must have pointer-to-object type)
expression must have pointer-to-object type
Stack is being implemented as an array And then there's this error.
What should I do?
Is this a Syntex error? Tell me the wrong part.
and If there is anything else that needs to be corrected, please let me know.
C language is difficult. Have you all experienced this kind of error?
return stack[top--]; same as return 100[top--];.
I suspect you wanted return st[top--];
Use a different name for the stack size too to avoid such name collisions.
// #define stack 100
#define STACK_SIZE 100
I see 3 problems:
A simple typo:
return stack[top--]; ==> return st[top--];
stack is the array size but your array is named st
Missing return value
This code has no return value when the stack is empty.
int pop() {
if (IsEmpty() == true)
printf("stack is empty.");
// No return value here
else
Even if the stack is empty you must return a value. So you need to handle that in another way. One option is to return a dummy value (e.g. zero), another is to exit the program or change the pop-function signature so that it can tell whether it was succesful. For instance:
// Option 1: Return dummy value
int pop() {
if (IsEmpty()) return 0;
return stack[top--];
}
// Option 2: Exit program
int pop() {
if (IsEmpty()) exit(1);
return stack[top--];
}
// Option 3: Let the function tell whether is was a success
int pop(int* data) {
if (IsEmpty()) return 0;
*data = stack[top--];
return 1;
}
The last pop-function returns 1 on success - zero otherwise.
Wrong logic
This function:
int IsEmpty()
{
if (top < 0)
return false;
else
return true;
}
is wrong. Change it to:
int IsEmpty()
{
if (top < 0)
return true;
else
return false;
}
or more simple
int IsEmpty()
{
return (top < 0);
}

Not able to figure out the logical error in my code

There is some logical error in my code but I'm not able to figure out what it is. When I run my code it doesn't give me desired results.
OUTPUT:
Enter an infix expression
2+3
2
I get 2 as my postfix expression whereas I should be getting 23+.
Please see if anyone could help me out with this one.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#define max 20
int top=-1;
char infix[max],postfix[max],stack[max];
char pop();
int empty();
void push(char );
int precedence(char );
void infix_to_postfix(char * ,char * );
void main()
{
clrscr();
printf("Enter an infix expression\n");
gets(infix);
infix_to_postfix(infix,postfix);
printf("%s",postfix);
getch();
}
void infix_to_postfix(char infix[max],char postfix[max])
{
int i=0,j=0;
char value,x;
for(i=0;infix[i]!='\0';i++)
{
value=infix[i];
if(isalnum(value))
{
postfix[j]=value;
j++;
}
else
{
if(value=='(')
push('(');
else
{
if(value==')')
{
while((x=pop())!='(')
{
postfix[j]=x;
j++;
}
}
else
{
while(precedence(value)<=precedence(stack[top])&&!empty())
{
x=pop();
postfix[j]=x;
j++;
}
push(value);
}
}
}
}
while(!empty())
{
x=pop();
postfix[j]=x;
j++;
}
postfix[j]='\0';
}
void push(char x)
{
if(top==max-1)
printf("stack overflow\n");
else
{
top++;
stack[top]=x;
}
}
char pop()
{
char x;
x=stack[top];
top--;
return x;
}
int empty()
{
if(top==-1)
return(0);
return(1);
}
int precedence(char value)
{
if(value=='(')
return(0);
if(value=='+'||value=='-')
return(1);
if(value=='*'||value=='/'||value=='%')
return(2);
return(3);
}
Generally, the logic of your code is OK except a return value mistake in the empty() function.
In the empty(), it should return 1 while stack is empty.
int empty(){
if(top==-1)
return(0); <-- !!! here should return 1
}
Otherwise,
it will go into the while loop at while(precedence(value)<=precedence(stack[top])&&!empty()) even when stack is empty.
And then postfix[j] = x may write a redundant 0(now top= -2) to postfix array.
Finally,under the input 2+3, the postfix[] will be {'2','\0','3','+',...}, which result in the abnormal output 2.
So, it will work after modifying the empty() function, such as
int empty()
{
if(top==-1)
return(1); // not return(0)
return(0);
}
Output:
Enter an infix expression
2+3
23+
all you need to do is change your empty() function
you are checking for !empty() in if condition, but you are returning 0, when it is empty, this will make the condition true, i.e. Stack is not empty. Change the return value to 1 in case of empty stack.

Missing prototype in my practice arithmetic quiz program, and almost every other program I make

Yesterday I was able to make a program (ASCII converter etc etc) that had the same problem [ Every function had a missing prototype error when I build the program ] I was able to fix it through random trial and error having no idea how I did it. Here's my arithmetic quiz practice program. I also tried putting int initialize(),clear(),exit(),additionquiz(),subtractionquiz(),divisionquiz(),multiplicationquiz(); and it still gave me a missing prototype.
#include <stdio.h>
/* Main Menu */
int numbers[10];
int main()
{
while(1==1)
{
int choice;
initialize();
printf("Arithmetic Quiz Program\n");
printf("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division\n5 - Exit\n");
scanf("%d",&choice);
if(choice==1)
{
clear();
additionquiz();
}
else if(choice==2)
{
clear();
subtractionquiz();
}
else if(choice==3)
{
clear();
multiplicationquiz();
}
else if(choice==4)
{
clear();
divisionquiz();
}
else if(choice==5)
{
exit();
}
else
{
printf("%cPlease choose a number from 1 - 5",7);
clear();
continue;
}
}
return 0;
}
/* For clearing the page */
int clear()
{
int i;
for(i=0;i<25;i++)
{
printf("\n");
}
}
/* Assigns the array */
int initialize()
{
numbers[0]=6;
numbers[1]=0;
numbers[2]=2;
numbers[3]=5;
numbers[4]=3;
numbers[5]=1;
numbers[6]=9;
numbers[7]=4;
numbers[8]=7;
numbers[9]=8;
return 0;
}
/* addition quiz */
int addition()
{
int a,diff,b,answer,choice;
a=0;
diff=1;
b=a+diff;
while(1==1)
{
if(a>9)
{
a=0;
diff++;
}
if(b>9)
{
b=0;
}
if(diff>9)
{
diff=0;
}
printf("%d + %d = ",number[a],number[b]);
scanf("%d",&answer);
if(answer==number[a]+number[b])
{
printf("\nCORRECT!!!\n");
a++;
}
else
{
printf("\nWRONG!!!\n");
clear();
additionquiz();
}
printf("\nWhat do you want to do next?\n1 - Answer another addition Question\n2 - Go back to main menu\n3 - Exit program\n");
scanf("%d",&choice);
if(choice==1)
{
clear();
additionquiz();
}
else if(choice==2)
{
clear();
main();
}
else if(choice==3)
{
exit();
}
else
{
printf("%cPlease choose a number from 1 to 3",7);
}
}
return 0;
}
/* The subtraction quiz */
int subtraction()
{
int a,diff,b,answer,choice;
a=0;
diff=1;
b=a+diff;
while(1==1)
{
if(a>9)
{
a=0;
diff++;
}
if(b>9)
{
b=0;
}
if(diff>9)
{
diff=0;
}
if(numbers[a]-numbers[b]<0)
{
a++;
subtraction();
}
printf("%d - %d = ",numbers[a],numbers[b]);
scanf("%d",&answer);
if(answer==numbers[a]-numbers[b])
{
printf("CORRECT!!!\n\n");
}
else
{
printf("WRONG!!!\n\n");
clear();
subtractionquiz();
}
printf("\nWhat do you want to do next?\n1 - Answer another subtraction Question\n2 - Go back to main menu\n3 - Exit program\n");
scanf("%d",&choice);
if(choice==1)
{
clear();
subtractionquiz();
}
else if(choice==2)
{
clear();
main();
}
else if(choice==3)
{
exit();
}
else
{
printf("%cPlease choose a number from 1 to 3",7);
}
}
return 0;
}
/* multiplication quiz */
int multiplicationquiz()
{
int a,diff,b,answer,choice;
a=0;
diff=1;
b=a+diff;
while(1==1)
{
if(a>9)
{
a=0;
diff++;
}
if(b>9)
{
b=0;
}
if(diff>9)
{
diff=0;
}
printf("%d * %d = ",number[a],number[b]);
scanf("%d",&answer);
if(answer==number[a]*number[b])
{
printf("\nCORRECT!!!\n");
a++;
}
else
{
printf("\nWRONG!!!\n");
clear();
multiplicationquiz();
}
printf("\nWhat do you want to do next?\n1 - Answer another multiplication Question\n2 - Go back to main menu\n3 - Exit program\n");
scanf("%d",&choice);
if(choice==1)
{
clear();
multiplicationquiz();
}
else if(choice==2)
{
clear();
main();
}
else if(choice==3)
{
exit();
}
else
{
printf("%cPlease choose a number from 1 to 3",7);
}
}
return 0;
}
/* Division quiz */
int divisionquiz()
{
int a,diff,b,answer,choice,remain;
a=0;
diff=1;
b=a+diff;
while(1==1)
{
if((numbers[a]<numbers[b])||numbers[b]==0)
{
a++;
clear();
divisionquiz();
}
if(a>9)
{
a=0;
diff++;
}
if(b>9)
{
b=0;
}
if(diff>9)
{
diff=0;
}
printf("%d % %d = \n",numbers[a],numbers[b]);
printf("What is the whole number?\n");
scanf("%d",&answer);
printf("What is the remainder? (0 if none\n)");
scanf("%d",&remain);
if(answer==numbers[a]/numbers[b] && remain==numbers[a]%numbers[b])
{
printf("\nCORRECT!!!");
a++;
}
else
{
printf("\nWRONG!!!");
clear();
divisionquiz();
}
printf("\nWhat do you want to do next?\n1 - Answer another division Question\n2 - Go back to main menu\n3 - Exit program\n");
scanf("%d",&choice);
if(choice==1)
{
clear();
divisionquiz();
}
else if(choice==2)
{
clear();
main();
}
else if(choice==3)
{
exit();
}
else
{
printf("%cPlease choose a number from 1 to 3",7);
}
}
return 0;
}
exit is an external function and you need to include its header at the top of your source code:
#include <stdlib.h> // exit
Please notice that in the function call the addition function is called addition and in the function definition additionquiz. Same for the substraction.
For the other functions, you should declare them before you call them: that is before the main function definition.
int initialize(void);
int clear(void);
int additionquiz(void);
int subtractionquiz(void);
int divisionquiz(void);
int multiplicationquiz(void);
int main(void)
{
/* ... */
Note that declaring all the functions in one go like this:
int initialize(void), clear(void), additionquiz(void),
subtractionquiz(void), divisionquiz(void), multiplicationquiz(void);
is permitted but it is not very readable and may surprise the reader.
Finally, if these functions are not called from another source code, you should tell the reader (and the compiler) by adding a static specifier at the beginning of the declaration like this:
static int clear(void); // the function is only called in this source code
The C compiler works from top-to-bottom. It must know that your functions exist before you attempt to call them. So you have two choices:
Define your functions above main (i.e. move the entire function bodies).
Declare your functions above main. i.e. put int initialize();, etc. above main.
Note also that in C, int initialize() is different to int initialize(void). You should be using the second version.
More information on what the guy above me just said can be found here. This page gives you an overview of how to suppress or enable different kinds of warnings in your code:
http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
Also another tip. You wrote a couple while loops in your code with this syntax:
while (1==1)
{
...
}
this will do the same thing
while(1)
{
}
Here's why: A while loop, an if statement, else statement, and an else if statement will
all perform the code beneath them if the code inside the parenthesis is true. Since 1 in C is true and 0 is false, my while loop above works the same as yours.
First, learn to compile with all warnings enabled and with debugging information (e.g. with gcc -Wall -g on Linux). Then improve your program till no warnings are given by the compiler (trust the compiler).
Then, learn to have a declaration for each of your function. Start your sole source file with them, or, if you have several source files, make a header file with them.
So you could add just after your #include lines:
// clear the screen
void clear(void);
// initialize the numbers
int initilize(void);
// addition quiz
int addition(void);
// subtraction quiz
int subtraction(void);
// multiplication quiz
int multiplicationquiz(void);
// division quiz
int divisionquiz(void);
By the way, your functions might be better named, and you could have formal arguments in them (else use void as the argument list). And I don't understand why they all return an int which you don't use.

mouse not taking input

I am trying to implement mouse interfecing but somethings wrong with the input function.It should tell me that wheater i have made a left click or a right click but its not printing anything.Have a look:
#include<graphics.h>
#include<dos.h>
union REGS in,out;
void Graphics(void);
void DetectMouse(void);
void ShowMouse(void);
void HideMouse(void);
void InputMouse(void);
int main()
{
Graphics();
DetectMouse();
ShowMouse();
// HideMouse();
InputMouse();
getch();
closegraph();
return 0;
}
void Graphics(void)
{
int driver=DETECT,mode;
initgraph(&driver,&mode,"C:\\TC\\bgi");
outtextxy(1,1,"Graphics mode activated!");
}
void DetectMouse(void)
{
int result;
in.x.ax=0;
result=int86(0x33,&in,&out);
if(result)
{
outtextxy(10,10,"Driver succesfully detected");
}
else
{
outtextxy(10,10,"Driver not detected");
}
}
void ShowMouse(void)
{
in.x.ax=1;
int86(0x33,&in,&out);
}
void HideMouse(void)
{
in.x.ax=2;
int86(0x33,&in,&out);
}
void InputMouse(void)
{
for(;kbhit();)
{
int x,y;
in.x.ax=3;
int86(0x33,&in,&out);
if(out.x.bx==1)
outtextxy(30,30,"Left click");
if(out.x.bx==2)
outtextxy(40,40,"Right click");
if(out.x.bx==3)
outtextxy(50,50,"Middle click");
delay(100);
}
}
Try if((out.x.bx & 1) != 0) ... - i.e. check just bit 0 - I note that many of the flags are 'unused' for INT33 AX=3 - whether this guarantees them zero or not is anyone's guess.
You probably want to have a main loop. INT 33 AX=0003 doesn't block waiting for mouse input.

Resources