In my java program I want to perform stack operation like push and pop. I also want to push string in stack operation but when I try to push string. I get error mentioned in screenshot. How should I change push method in order to run the program successfully.
code ::
public class DataStack {
private static final int capacity = 3;
String arr[] = new String[capacity];
int top = -1;
public void push(String pushedElement) {
if (top < capacity - 1) {
top++;
arr[top] = pushedElement;
printElements();
} else {
System.out.println("Stack Overflow !");
}
}
public void pop() {
if (top >= 0) {
top--;
System.out.println("Pop operation done !");
} else {
System.out.println("Stack Underflow !");
}
}
public void printElements() {
if (top >= 0) {
System.out.print("Elements in stack : ");
for (int i = 0; i <= top; i++) {
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
DataStack stackDemo = new DataStack();
stackDemo.push("china");
stackDemo.push("india");
stackDemo.push("usa");
}
}
Error::
Your push() method and underlying arr variable should be of String type.
String arr[] = new String[capacity];
public void push(String pushedElement) {
...
}
Your array is declared to store only integers . Not to mention, the stackDemo.push method also declared to take in only int arguments.
int arr[] = new int[capacity];
public void push(int pushedElement) {
you should try pushing in integers.
stackDemo.push(1);
stackDemo.push(2);
stackDemo.push(3);
Related
Good evening everyone, sorry for bothering.
I have a problem while trying to configure the "DynamicArray" by myself. Here I made a sort method but the terminal shows "error:unexpected type", I actually have some difficulty of solving this, can some one help me to check what's the problem I have?
Thanks in advance.
Here is my code:
package lab2;
public class DynamicArray {
private static int INITIAL_CAPACITY = 5;
private int[] data;
private int size;
public DynamicArray() {
data = new int[INITIAL_CAPACITY];
size = 0;
}
// Returns `true` if the array is empty.
public boolean isEmpty() {
if (size==0){
return true;
}
else{
return false;
}
}
// Returns the size of the array.
public int size() {
return size;
}
// Remove all elements from data.
public void clear() {
size=0;
}
// Create a `String` with the elements of the array separated by comma, without a new line character at the end.
// For instance: 4, 5, 6
public String toString() {
if(size==0){
return "";
}
StringBuilder a = new StringBuilder();
for(int i=0;i<size;i++){
if(i==size-1){
a.append(data[i]);
}
else{
a.append(data[i]).append(",").append(" ");
}
}
return a.toString();
}
// Returns `true` if the array `data` is full: no more element can be added to `data`.
// Returns `false` otherwise.
private boolean isFull() {
if(size==data.length){
return true;
}
return false;
}
// If the array `data` is full:
// 1. Create a new array `data2` doubling the size of data.
// 2. Copy the elements of `data` into `data2`.
// 3. Assign `data2` to `data`.
private void realloc() {
if(size==data.length){
int [] data2 = new int[data.length*2];
System.arraycopy(data, 0, data2, 0,data.length);
data=data2;
}
}
// The element `x` is added to `data`, and `size` is incremented by one.
// `data` is automatically resized if it is too small.
public void add(int x) {
realloc();
data[size++]=x;
}
private void checkIndex(int idx) {
if(idx >= size) {
throw new ArrayIndexOutOfBoundsException();
}
}
// Set the ith element of `data` to `x`.
public void set(int idx, int x) {
int a = data[idx];
data[idx]=x;
}
// Return the element at the index `idx` of `data`.
public int get(int idx) {
checkIndex(idx);
return data[idx];
}
// Remove the element at index `idx`.
// Shift all the elements after `idx` of one position to the left.
public void remove(int idx) {
checkIndex(idx);
for(int i = idx; i<size-1; i++){
data[i]=data[i+1];
}
size--;
}
}
And the code which the problem appear:
package lab2;
public class DynamicArrayTest {
public static void main(String[] args) {
DynamicArray array = new DynamicArray();
testAdd(array);
testRemove(array);
testGet(array);
testRealloc(array);
testSort(array);
}
public static void testAdd(DynamicArray array) {
System.out.println("Test add method.");
System.out.println(array.size());
System.out.println(array.isEmpty());
array.clear();
System.out.println(array.size());
System.out.println(array.isEmpty());
array.add(4);
array.add(5);
array.add(6);
System.out.println(array);
}
public static void testRemove(DynamicArray array) {
System.out.println("Test remove method.");
try {
for(int i = 0; i < 3; ++i) {
array.remove(1);
System.out.println(array);
System.out.println(array.size());
System.out.println(array.isEmpty());
}
}
catch(ArrayIndexOutOfBoundsException e) {}
array.remove(0);
System.out.println(array);
System.out.println(array.size());
System.out.println(array.isEmpty());
}
public static void testGet(DynamicArray array) {
System.out.println("Test get method.");
try {
array.get(4);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("OK");
}
}
public static void testRealloc(DynamicArray array) {
System.out.println("Test realloc method.");
for(int i = 0; i < 100; ++i) {
array.add(i);
}
System.out.println(array);
while(!array.isEmpty()) {
array.remove(0);
}
System.out.println(array);
System.out.println(array.size());
System.out.println(array.isEmpty());
}
public static void testSort(DynamicArray array){
System.out.println("Sort the array.");
for(int i =0; i<array.size(); ++i){
for (int j=0; j<array.size() - i; ++j){
if (array.get(j-1)<array.get(j)){
int a = array.get(j-1);
array.get(j-1)=array.get(j);
array.get(j)=a;
}
}
}
}
}
And the error code:
public static void testSort(DynamicArray array){
System.out.println("Sort the array.");
for(int i =0; i<array.size(); ++i){
for (int j=0; j<array.size() - i; ++j){
if (array.get(j-1)<array.get(j)){
int a = array.get(j-1);
array.get(j-1)=array.get(j);
array.get(j)=a;
}
}
}
}
Again, the terminal shows:
src/lab2/DynamicArrayTest.java:72: error: unexpected type
array.get(j-1)=array.get(j);
^
required: variable
found: value
src/lab2/DynamicArrayTest.java:73: error: unexpected type
array.get(j)=a;
^
required: variable
found: value
2 errors
Thanks a lot for your help.
array.get(j-1)=array.get(j);
array.get(j)=a;
should be
array.set(j-1, array.get(j));
array.set(j, a);
This line is trying to assign a value to a value. The left side of this statement would need to be a variable. You did the same mistake in multiple places.
array.get(j-1)=array.get(j);
You either need to assign the value of array.get(j) to a variable or call a setter on the array object, setting the position of j-1 to the value returned by array.get(j). Depending on what you want to do with the value.
I have created a function "m7" in my class but this function is always returning value getting multiplied by 2.
If I am running this function in "psvm" it is printing the right value.
In my Alice class, the method m7() is returning 10 which is incorrect but if I am running this method in psvm then it is returning 5 which is correct.
package com.math.functions;
import java.util.*;
public class Alice {
Integer[] rank= new Integer[7];
Integer n=65;
int count=0;
public Alice() {
rank[0]=100;
rank[1]=100;
rank[2]=90;
rank[3]=80;
rank[4]=75;
rank[5]=60;
rank[6]=n;
//rank[6]=20;
//rank[7]=10;
//rank[8]=n;
Arrays.sort(rank, Collections.reverseOrder());
}
public void print() {
for (Integer a : rank) {
System.out.println(a);
}
}
public int m7() {
for (int i = 0; i < rank.length; i++) {
if (rank[i] == n) {
break;
}
count++;
}
return count;
}
public void res(){
int s = m7();
System.out.println("this is the value of s here :"+s);
Set<Integer> hash_Set = new HashSet<>();
for(int i=0;i<=s/2;i++){
System.out.println("hii");
hash_Set.add(rank[i]);
}
for(Integer o:hash_Set){
System.out.println(o);
System.out.println("rank:"+hash_Set.size());
}
}
public static void main(String[] args) {
Alice a=new Alice();
a.print();
System.out.println("this is: "+a.m7());
a.res();
}
}
You are reusing the value of count from the previous time you run it.
Don't declare count as a member variable, make it a local variable.
public int m7() {
int count = 0; // HERE
for (int i = 0; i < rank.length; i++) {
if (rank[i] == n) {
break;
}
count++;
}
return count;
}
This may be a very simple question, but I can't seem to find a suitable answer on Google. I have a class called Player, which has a String array called playerInv with a size of 10.
In my Main Activity Class, I want to run a for loop to determine the first index in the array that is empty (""). I then want to populate that with a new string, and then terminate the loop. How do I do this?
Sorry for the nooby question. Like I said, I've tried Google to no avail!
For Loop:
String playerInvTemp[] = thePlayer.getPlayerInv; ERROR -- cannot resolve getPlayerInv
for (int i=0; i < playerInvTemp.length; i++)
{
if ((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i); ERROR cannot resolve setPlayerInv
//invText.setText();
Blood = true;
break;
}
}
Player Class:
public class Player {
private int playerPos;
private int playerHP;
private String playerInv[];
Player(int startPos, int startHP, String[] newInventory)
{
playerPos = startPos;
playerHP = startHP;
playerInv = newInventory;
}
public int getPlayerPos() {
return playerPos;
}
public void setPlayerPos(int playerPos) {
this.playerPos = playerPos;
}
public int getPlayerHP(){
return playerHP;
}
public void setPlayerHP(int playerHP){
this.playerHP = playerHP;
}
public String getPlayerInv(int pos)
{
return playerInv[pos];
}
public void setPlayerInv(String playerInv[]) {
for (int i=0; i<10; i++)
{
this.playerInv[i] = playerInv[i];
}
}
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String getPlayerInv()
{
return this.playerInv; *//this gives error "Incompatible types. Required java.lang.string, found java.lang.string[]"*
}
}
Do this
Add these two method in Player class
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String[] getPlayerInv()
{
return this.playerInv;
}
then change your for loop like this
String playerInvTemp[] = thePlayer.getPlayerInv();
for (int i=0; i < playerInvTemp.length; i++)
{
if (!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i);
//invText.setText();
Blood = true;
break;
}
}
Bunch of problems here, .length() is not valid for an array, it should be .length.
`for (int i=0; i<thePlayer.getPlayerInv(i).length(); i++)`
You most likely mean null or at least need to check for it, here and you need [] not ():
if (thePlayer.getPlayerInv[i] == "" or theplayer.getPlayerInv[i] == null)
This is all wrong, and as a matter of fact you need to post your code and errors, you have many problems and should start with learning some basics about Java.
Try some beginners tutorials (https://www.google.com/search?q=java+tutorials&ie=utf-8&oe=utf-8). You have a lot of both syntax and logic errors.
Do you run an instance of constructor player()??
I did
Player a=new Player();
a.getPlayerInv(0)
and works fine.
I am writing a program to reverse a word using a stack data structure. The way it's supposed to work is that I input a string, insert each character of the string in a stack object, then I would pop each object out of the stack and print them. The word will be in the reverse order of the original input since that's just how stacks work.
I keep getting an index out of bounds exception; debugging makes me suspect that it has to do with the initial array initialization within the Stack class, but it could also have to do with the push() function.
Here's the entire code:
public class Stack // object to emulate stack data structure
{
private int stackMaxSize;
private char stackArray[];
private int currentSize;
public Stack() // if initialized without any parameters
{
this(100);
}
public Stack(int maxSize) // if initialized with parameter
{
maxSize = stackMaxSize;
stackArray = new char[stackMaxSize];
currentSize = -1;
}
public void push(char c) //pushes new character into stack
{
stackArray[++currentSize] = c;
}
public char pop() //pops character out of stack
{
return stackArray[currentSize--];
}
public char peek() // returns character on top of stack
{
return stackArray[currentSize];
}
public boolean isEmpty() // returns whether stack is empty or not
{
return (currentSize < 0);
}
}
and here's the main:
import java.util.Scanner;
public class ReverseWord
{
public static void main(String[] args)
{
Stack wordStack = new Stack(100); // default size is 100
System.out.print("Enter the word to be reversed: ");
String word = getString();
for (byte i = 0; i <= word.length(); i++) // inserts word into stack char by char
{
wordStack.push(word.charAt(i));
}
System.out.print(wordStack.pop());
}
static String getString()
{
Scanner input = new Scanner(System.in);
String s = input.nextLine();
return s;
}
}
Thanks a lot!
JLL
In your Stack(int) constructor
maxSize = stackMaxSize;
should be
stackMaxSize = maxSize;
The corrected and working code as follows: (Note that, the main function is written in Stack class for simplicity and corrected code lines are commented)
public class Stack // object to emulate stack data structure
{
private final int stackMaxSize;
private final char stackArray[];
private int currentSize;
public Stack() // if initialized without any parameters
{
this(100);
}
public Stack(final int maxSize) // if initialized with parameter
{
this.stackMaxSize = maxSize; /* corrected: assignment reversed */
this.stackArray = new char[this.stackMaxSize];
this.currentSize = -1;
}
public void push(final char c) // pushes new character into stack
{
this.stackArray[++this.currentSize] = c;
}
public char pop() // pops character out of stack
{
return this.stackArray[this.currentSize--];
}
public char peek() // returns character on top of stack
{
return this.stackArray[this.currentSize];
}
public boolean isEmpty() // returns whether stack is empty or not
{
return this.currentSize < 0;
}
public static void main(final String[] args) {
Stack wordStack = new Stack(100); // default size is 100
System.out.print("Enter the word to be reversed: ");
String word = getString();
/* corrected: i <= word.length() >> i < word.length() */
for (byte i = 0; i < word.length(); i++) // inserts word into stack char by char
{
wordStack.push(word.charAt(i));
}
/* corrected: while loop added to consume the entire stack */
while (!wordStack.isEmpty()) {
System.out.print(wordStack.pop());
}
}
static String getString() {
Scanner input = new Scanner(System.in);
String s = input.nextLine();
return s;
}
}
The problems with the original program was that:
1) For loop should be:
for (byte i = 0; i < word.length(); i++)
instead of <= (thanks to ovunccetin)
2) In the constructor of the Stack class
maxSize = stackMaxSize;
should be:
stackMaxSize = maxSize;
Thanks to Ravi Thapliyal
Pretty simple idea, I am just not sure why it won't work. I am getting an error when I call Stack b = new Stack(5); in main.
Here is main
public class Test {
public static void main(String[] args) {
Stack b = new Stack(5);
b.push('a');
b.push('b');
b.push('c');
b.printStack();
}
}
Here is my stack class
public class Stack {
char[] stack;
int items;
public Stack(int size) {
stack = char[size];
items = 0;
}
public void push (char add){
if (items == stack.length) {
System.out.println("Stack is full");
}
else {
stack[items] = add;
}
}
public void printStack() {
if (items == 0)
return;
else {
for (int i = 0; i < items; i++)
System.out.println(i);
}
}
}
One thing is:
public Stack(int size) {
stack = new char[size];
//^^^you missed new
items = 0;
}
Meanwhile
stack[items] = add; //should also increment items
You need to new up your array.
I can see that your push doesn't increment the items count. When you push onto your stack, you should also increment the count.
in your constructor use
stack = new char[size];
You are not using the new keyword when creating your stack array in the constructor.
Furthermore, your push() method does not increment items, and thus will simply constantly overwrite the first element of the stack array.
Finally, your printStack() method will not function as you expect it to. Rather, it will print incremental digits up to the number 5. You will need to change the print statement for it to work.
System.out.println(stack[i]);