I am trying to understand stacks with Objects, so I typed this out, but the problem is that I am getting this really weird message that I can't make sense of. It says "Exception in thread "main" java.lang.NoSuchMethodError: Stack.push(Ljava/lang/Object;)V
at TestObjectStack.main(TestObjectStack.java:12)". I googled it, but I still can't figure out what I'm doing wrong. I redid the main method header, but that didn't fix it. Does anyone have any suggestions or insight that I am missing? Thanks a lot!:
public class TestObjectStack
{
public static void main(String[] args)
{
Object o;
Stack test = new Stack();
test.push("Fred");
test.push(20);
test.push(new ThingB("Barney", 42));
Stack copy = new Stack(test);
System.out.println("Stack test: " + test);
System.out.println(test.pop());
System.out.println("Stack test: " + test);
System.out.println("Stack copy: " + copy);
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a String");
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a string");
if(test.isEmpty()) System.out.println("empty");
}
}
class ThingB
{
private String _name;
private int _ID;
public ThingB(String name, int ID)
{
_name = name;
_ID = ID;
}
public String toString()
{
return "Thing B - name - " + _name + " ID = " + _ID;
}
}
class Stack
{
private Object[] _store;
private int _top;
private static final int MAXSIZE = 50;
public Stack()
{
_store = new Object[MAXSIZE];
_top = 0;
}
public Stack(Stack other)
{
_store = new Object[other._store.length];
_top = other._top;
for(int i = 0; i < _top; ++i)
{
_store[i] = other._store[i];
}
}
public boolean isEmpty()
{
return (_top == 0);
}
public void push(Object item)
{
if(_top >= _store.length)
{
Object[] temp = new Object[_store.length+ MAXSIZE];
for(int i = 0; i < _top; ++i)
{
temp[i] = _store[i];
}
_store = temp;
}
_store[_top] = item;
++_top;
}
public Object pop()
{
if(_top == 0) return 0;
--_top;
return _store[_top];
}
public String toString()
{
String s = "";
s = s + "--Top--";
for(int i = _top-1; i >= 0; --i)
{
s = s + " " + _store[i];
}
s = s + "--Bottom--";
return s;
}
}
I executed your code in the IDE: IntelliJ IDEA. And I have the following result:
Stack test: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
Thing B - name - Barney ID = 42
Stack test: --Top-- 20 Fred--Bottom--
Stack copy: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
20
Not a String
Fred
String length = 4
empty
Your source code is working fine, maybe you need to adjust your IDE parameters. Try with a simple "Hello World" program.
Best regards,
Alvaro
Related
Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}
I have an arraylist of year and value. this arraylist is place in a linkedlist as one of element in the linkedlist.
linkedlist elements -> countrycode, indicatorName, indicatorCode and data (arraylist)
how can i retrieve the value from the arraylist when i search for the indicator code and then the year?
segments of my code from application class:
while(str2 != null ){
StringTokenizer st = new StringTokenizer(str2,";");
ArrayList <MyData> data = new ArrayList();
String cCode = st.nextToken();
String iName = st.nextToken();
String iCode = st.nextToken();
for (int j = 0; j < 59; j++){
String v = st.nextToken();
int year = 1960 + j;
d1 = new MyData (year,v);
data.add(d1);
}
Indicator idct1 = new Indicator (cCode,iName,iCode,data);
bigdata.insertAtBack(idct1);
str2 = br2.readLine();
}
//search
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(bigdata,search3);
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
public static void searchYear (myLinkedList bigdata, int searchTerm) {
Indicator idct4 = (Indicator)bigdata.getFirst();
boolean found = false;
while(idct4 != null){
if(idct4.getDYear() == searchTerm) {
found = true;
System.out.println(idct4.getDValue());
}
idct4 = (Indicator)bigdata.getNext();
}
if (!found){
String message = "Error!";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",JOptionPane.ERROR_MESSAGE);
}
}
indicator class:
public Indicator(String cCode, String iName, String iCode,ArrayList <MyData> DataList){
this.cCode = cCode;
this.iName = iName;
this.iCode = iCode;
this.DataList = DataList;
}
public String getCCode(){return cCode;}
public String getIName(){return iName;}
public String getICode(){return iCode;}
public int getDYear(){return d.getYear();}
public String getDValue(){return d.getValue();}
public void setCCode(String cCode){this.cCode = cCode;}
public void setIName(String iName){this.iName = iName;}
public void setICode(String iCode){this.iCode = iCode;}
public String toString(){
return (cCode + "\t" + iName + "\t" + iCode + "\t" + DataList.toString());
}
}
MyData class:
public MyData(int year, String value){
this.year = year;
this.value = value;
}
public int getYear(){return year;}
public String getValue(){return value;}
public void setYear(int year){this.year = year;}
public void setValue(String value){this.value = value;}
public String toString(){
return (value + "(" + year + ")");
}
I can't add a comment yet, but here's what I'm assuming.
Here it's getting a matching Indicator code (iCode), so let's pass the Indicator object (idct3) into searchYear method instead to focus on its ArrayList < MyData > DataList:
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(idct3,search3); // Indicator passed in here
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
Let's change searchYear method to take the Indicator class and search its DataList:
public static void searchYear (Indicator indicator, int searchTerm) {
for (int i = 0; i < indicator.DataList.size(); i++) {
if (indicator.DataList.get(i).getYear() == searchTerm) { // Sequentially get MyData object from DataList and its year for comparison
System.out.println("Found year " + searchTerm + " with Indicator code " + indicator.getICode() + " having value " + indicator.DataList.get(i).getValue());
return; // Exit this method
}
}
System.out.println("Not Found");
}
I have a program where i select an option to add ship, which prompts me to give an id e.g b 2. it then prompts me to enter a capacity. However, I am using a search method to prevent any repeat id's that I may enter a second time round. The program compiles, but my statement "Ship id is already in use" won't print out. Any ideas please?
Here is my code.
public int search(String id)
{
for(int index = 0; index < ships.length && ships[index] != null; ++index)
{
shipId = id;
if (ships[index].getId().equals(id))
{
return index;
}
}
//ship id not found so you can add ship
return -1;
}
public void addShip( )
{
System.out.println("Enter ship id >> ");
String id = kb.nextLine();
if(id.equals(search(id)))
{
System.out.println("Ship id already in use");
return;
}
else
{
//for(int i = 0; i < ships.length; ++i)
{
System.out.println("Enter ship capacity");
int capacity = kb.nextInt();
ships[shipCounter++] = new Ship(id, capacity);
}
}
}
Here is my ship class:
public class Ship
{
private String id;
private int capacity;
private int currentCrew; // index into the Crew array
// points to the next free space
// in the Crew array
private String status;
private Crew [ ] crew;
public Ship(String id, int capacity)
{
this.id = id;
this.capacity = capacity;
this.currentCrew = 0;
crew = new Crew[capacity];
}
public Ship(String id, int capacity, String status)
{
this.id = id;
this.capacity = capacity;
this.status = "available";
this.currentCrew = 0;
crew = new Crew[capacity];
}
public void setId(String newId)
{
id = newId;
}
public void setCapacity(int newCapacity)
{
capacity = newCapacity;
}
public void setStatus(String newStatus)
{
if(status.equals("available"))
{
newStatus = "on station";
status = newStatus;
}
else if(status.equals("on station"))
{
newStatus = "maintenance";
status = newStatus;
}
else if(status.equals("station") || status.equals("maintenance"))
{
newStatus = "available";
status = newStatus;
}
else
{
System.out.println("Invalid status");
}
}
public String getId()
{
return id;
}
public String getStatus()
{
return status;
}
public int getCapacity()
{
return capacity;
}
public int getCurrentCrew()
{
return currentCrew;
}
public void addCrew()
{
//if(currentCrew < capacity)
{
//System.out.println("Enter crew id >> ");
//String id = kb.nextLine();
}
}
public String toString()
{
String sdesc =
'\n'
+ "Ship"
+ '\n'
+ "["
+ '\n'
+ " "
+ "Id: " + id
+ " capacity: " + capacity
+ " current crew: " + currentCrew
+ " status: " + status
+ '\n'
+ "]";
return sdesc;
}
}
Did you noticed this line
if(id.equals(search(id)))
id is String type, but search return type is int.
if you see in String class equals method,
if (anObject instanceof String) {
}
return false;
so its simply give false always
so the simple solution is convert that int to String.
something like
if(id.equals(search(id+"")))
If you'd like to see if you already have a ship with the id, you should check that the index exists, which is what your search method returns.
if(search(id) > 0)
{
System.out.println("Ship id already in use");
return;
}
I have created a class Hotel defined as follows:
import java.util.Random;
public class Hotel {
private Osoba[] tab = new Osoba[100];
public void zamelduj(Osoba os, int num) {
if (tab[num - 1] == null) {
System.out.println("Pokoj o numerze " + num + "jest zajety");
return;
}
tab[num - 1] = os;
}
public void wymelduj(int num) {
tab[num - 1] = null;
}
public void zamienOsoby(int num1, int num2) {
Osoba o = tab[num1 - 1];
tab[num1 - 1] = tab[num2 - 1];
tab[num2 - 1] = o;
}
public void znajdzWolnePokoje() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println(i + 1);
}
}
public void przydzielPokoje50() {
for (int i = 0; i < 50; i++) {
Random r = new Random();
Osoba o = new Osoba();
int num = r.nextInt(100);
tab[num] = o;
}
}
public void wypisz() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println("Pokoj nr. " + (i + 1) + " jest wolny");
else System.out.println("Pokoj nr. " + i + " jest zajety przez " + tab[i].imie + " " + tab[i].nazwisko);
}
}
public static void main(String[] args) {
Hotel h = new Hotel();
//h.przydzielPokoje50();
//h.wypisz();
h.zamelduj(null, 30);
}
}
I also have a class Osoba:
public class Osoba {
public String imie;
public String nazwisko;
Osoba() {
imie = null;
nazwisko = null;
}
Osoba(String imie, String nazwisko) {
this.imie = imie;
this.nazwisko = nazwisko;
}
}
I want to execute the method Zamelduj, which will assign a person (Osoba) to a cell in a table. However, every time I insert something other than null in the following it says that the first argument is not a capable parameter of the method.
h.zamelduj(null, 30);
What am I doing wrong?
I think your problem is that on the line " h.zamelduj(null, 30);" you need to create a new Osoba:
h.zamelduj(new Osoba("o.o", "._.!"), 30);
what happens is that the function is expecting a Osoba, if you give it another thing, it refuses. i hope it helps
You need to create an object of the class hotel (in your class from where you want to call the method type):
Hotel myObjectHotel = new Hotel();
And then you can call the method trough:
myHotelObject. zamelduj(give parameters here);
:)
Update:
Missed the real question. Just focused on the topic. I'm sorry. ;)
I'm new to java. When I compile my code on the terminal it is telling me I am getting several errors and I am not sure why. Most of the errors are "can't find symbol"
import java.util.Scanner;
public class CircularQueue {
private int head, tail;
private String [ ] q = new String [ 10 ];
private String name;
Scanner input = new Scanner (System.in);
public CircularQueue () {
head = -1;
tail = -1;
}
public void insertQueue () {
if (isQueueFull () )
System.out.println ("Overflow");
else {
name = getName ();
if (isQueueEmpty () )
head = +1;
if (tail==Size-1)
tail=-1;
q [++ tail] = name;
}
}
public void deleteQueue() {
String x;
if ( isQueueEmpty () )
System.out.println("Underflow");
else {
x=q[head];
System.out.println ("Servicing " + x);
if (head==tail) {
head=-1;
tail=-1;
}
else {
head ++;
if (head==Size)
head=0;
}
}
}
private String getName () {
System.out.println("Enter name");
return input.nextLine ();
}
public boolean isQueueEmpty () {
return (head==-1);
}
public boolean isQueueFull () {
return ((tail-head+1==0) || (tail-head+1==Size));
}
public void printQueueLogical () {
int next;
if (isQueueEmpty())
System.out.println ("Empty");
else {
next=head;
System.out.println (" q [" + next + "] = " +q[next]);
while (next != tail) {
next ++;
if (next==Size)
next=0;
System.out.println (" q [" + next + "] = " +q[next]);
}
}
}
public void printQueuePhysical () {
for (int J=0; J<Size; J++)
System.out.println (" q [" + J + "]= " + q [J]);
}
class TestCircularQueue {
public static void main ( strings [] args) {
CircularQueue n = new CircularQueue ();
for (int J=0; J<3; J++)
m.insertQueue ();
m.deleteQueue ();
m.printQueueLogical ();
}
}
}
When the compiler says it can't find a symbol, this means that you probably have a syntax error. A symbol can be a keyword, some method name, an operator, etc.
Possible causes, for example (extracted from http://java.about.com/od/cerrmsg/g/Definition-Cannot-Find-Symbol.htm)
trying to use a variable without declaring it.
misspelling a class or method name (remember, Java is case sensitive).
the parameters used do not match a method's signature.
the packaged class has not being referenced correctly using an import declaration.
What you can do?
You can read the stacktrace. The "can't find a symbol" exception usually comes with useful information, such as the offending symbol and the location in the code. For example (again, from the link above)
System.out.prontln("The perils of mistyping..");
will generate something like
cannot find symbol
symbol: method prontln(jav.lang.String)
location: class java.io.printStream
Just added some lines of code.Dint test your logic though and do not create unnecessary inner classes.
import java.util.Scanner;
public class CircularQueue {
private int head, tail;
private String [ ] q = new String [ 10 ];
private String name;
int Size;
Scanner input = new Scanner (System.in);
public CircularQueue () {
head = -1;
tail = -1;
}
public void insertQueue () {
if (isQueueFull () )
System.out.println ("Overflow");
else {
name = getName ();
if (isQueueEmpty () )
head = +1;
if (tail==Size-1)
tail=-1;
q [++ tail] = name;
}
}
public void deleteQueue() {
String x;
if ( isQueueEmpty () )
System.out.println("Underflow");
else {
x=q[head];
System.out.println ("Servicing " + x);
if (head==tail) {
head=-1;
tail=-1;
}
else {
head ++;
if (head==Size)
head=0;
}
}
}
public void setSize(int i)
{
Size=i;
}
private String getName () {
System.out.println("Enter name");
return input.nextLine ();
}
public boolean isQueueEmpty () {
return (head==-1);
}
public boolean isQueueFull () {
return ((tail-head+1==0) || (tail-head+1==Size));
}
public void printQueueLogical () {
int next;
if (isQueueEmpty())
System.out.println ("Empty");
else {
next=head;
System.out.println (" q [" + next + "] = " +q[next]);
while (next != tail) {
next ++;
if (next==Size)
next=0;
System.out.println (" q [" + next + "] = " +q[next]);
}
}
}
public void printQueuePhysical () {
for (int J=0; J<Size; J++)
System.out.println (" q [" + J + "]= " + q [J]);
}
}
class TestCircularQueue {
public static void main ( String [] args) {
CircularQueue n = new CircularQueue ();
n.setSize(10);
for (int J=0; J<3; J++)
{n.insertQueue ();
n.deleteQueue ();
n.printQueueLogical ();}
}
}
i Think "size" means the length of the Array....
ie. int size = q.length;
and for some reason when creating the object of the class you used 'n' and then when you wanted to use it you used 'm' check that also
so after going through it...i think dis worked for me..although what you are trynna achieve...but you should sort the rest yourself
import java.util.Scanner;
public class CircularQueue {
private int head, tail;
private String [ ] q = new String [ 10 ];
private String name;
int Size = q.length;
Scanner input = new Scanner (System.in);
public CircularQueue () {
head = -1;
tail = -1;
}
public void insertQueue () {
if (isQueueFull () )
System.out.println ("Overflow");
else {
name = getName ();
if (isQueueEmpty () )
head = +1;
if (tail==Size-1)
tail=-1;
q [++ tail] = name;
}
}
public void deleteQueue() {
String x;
if ( isQueueEmpty () )
System.out.println("Underflow");
else {
x=q[head];
System.out.println ("Servicing " + x);
if (head==tail) {
head=-1;
tail=-1;
}
else {
head ++;
if (head==Size)
head=0;
}
}
}
private String getName () {
System.out.println("Enter name");
return input.nextLine ();
}
public boolean isQueueEmpty () {
return (head==-1);
}
public boolean isQueueFull () {
return ((tail-head+1==0) || (tail-head+1==Size));
}
public void printQueueLogical () {
int next;
if (isQueueEmpty())
System.out.println ("Empty");
else {
next=head;
System.out.println (" q [" + next + "] = " +q[next]);
while (next != tail) {
next ++;
if (next==Size)
next=0;
System.out.println (" q [" + next + "] = " +q[next]);
}
}
}
public void printQueuePhysical () {
for (int J=0; J<Size; J++)
System.out.println (" q [" + J + "]= " + q [J]);
}
}
public class TestCircular {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CircularQueue n = new CircularQueue ();
n.insertQueue ();
n.deleteQueue ();
n.printQueueLogical ();
}
}