java how to execute method - java

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. ;)

Related

How to use array of objects in this context?

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();
}
}

Java NoSuchMethodError

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

JTable object [][] data

I am trying to create a table based on my trial class. When I try to run my table class the table prints with the proper heading, but it does not print anything in the body of the table. How should I fix my for loop so the data enters the table? Do I need to add a parameter to the constructor?
I understand there are more getters and setters than necessary. I was just trying to go about the for loop in different ways.
public class Trial extends JFrame{
static int counter = 0;
int laps = 0;
String lapTime;
double currentTime = 0;
String difference;
int lapsCount = 0;
String[] array1;
double[] array2;
double[] array3;
public int getLapsCount() {
return lapsCount;
}
public void setLapsCount(int lapsCount) {
this.lapsCount = lapsCount;
}
public static int getCounter() {
return counter;
}
public static void setCounter(int counter) {
Trial.counter = counter;
}
public int getLaps() {
return laps;
}
public void setLaps(int laps) {
this.laps = laps;
}
public String getLapTime() {
return lapTime;
}
public void setLapTime(String lapTime) {
this.lapTime = lapTime;
}
public double getCurrentTime() {
return currentTime;
}
public void setCurrentTime(double currentTime) {
this.currentTime = currentTime;
}
public String getDifference() {
return difference;
}
public void setDifference(String difference) {
this.difference = difference;
}
public String[] getArray1() {
return array1;
}
public void setArray1(String[] array1) {
this.array1 = array1;
}
public double[] getArray2() {
return array2;
}
public void setArray2(double[] array2) {
this.array2 = array2;
}
public double[] getArray3() {
return array3;
}
public void setArray3(double[] array3) {
this.array3 = array3;
}
public static void main(String[] args) {
//drop down for number of laps
String lapsString;
String[] selections = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
lapsString = (String) JOptionPane.showInputDialog(null,
"Choose a number of laps:",
"Lap Counter",
JOptionPane.INFORMATION_MESSAGE,
null, /* icon */
selections,
"0");
System.out.printf("Number of laps = \"%s\"\n", lapsString);
int lapsCount = Integer.parseInt(lapsString);
String[] array1 = new String[lapsCount+1];
double[] array2 = new double[lapsCount+1];
double[] array3 = new double[lapsCount+1];
// showInputDialog with for lap time
for (int i = 1; i <= lapsCount; i++){
String lapTime;
lapTime =
JOptionPane.showInputDialog("Enter lap " + i + " total time.");
System.out.printf("Lap " + i + " = \"%s\"\n", lapTime);
array1[i] = lapTime;
double currentTime = inputConvert(array1[i]);
array2[i] = currentTime;
array3[i] = (array2[i] - array2[i-1]);
counter++;
//confirm each time
int result;
String[] results = { "Yes", "No", "Cancel" };
result = JOptionPane.showConfirmDialog(null,
"Please confirm lap " + i + " is " + lapTime);
if (result == -1)
System.out.printf("user closed window\n");
else if (result == 0)
System.out.printf("result = %d, user pressed \"%s\"\n", result, results[result]);
else {
lapTime =
JOptionPane.showInputDialog("Please re-enter lap " + i);
System.out.printf("Lap " + i + " = \"%s\"\n", lapTime);
counter++;
}
}
}
public static double inputConvert(String s) {
double convert = 0.0;
int minutes = Integer.parseInt(s.substring(0, 1));
double seconds = Double.parseDouble(s.substring(2, s.length()));
minutes = minutes * 60;
convert = minutes + seconds;
return convert;
}
private static String getDifference(int j, double sign) {
String difference = "";
if(j == 0) {
difference = "---";
}
else if(sign > 0.0) {
difference = "+";
}
return difference;
}
public static String displayTime(double time) {
String result = null;
int minutes = (int) (time/60);
double seconds = (time % 60);
seconds = Math.round(seconds*100.0)/100.0;
if(seconds < 10){
result = minutes + ":0" + seconds;
}
else{
result = minutes + ":" + seconds;
}
return result;
}
}
This is my table class where the problem arises.
public class table {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new table();
}
});
}
public table() {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Table to record lap times");
guiFrame.setSize(700,200);
guiFrame.setLocationRelativeTo(null);
JTable table = new JTable(new ExampleTableModel());
table.setAutoCreateRowSorter(true);
table.setGridColor(Color.YELLOW);
table.setBackground(Color.CYAN);
JScrollPane tableScrollPane = new JScrollPane(table);
guiFrame.add(tableScrollPane);
guiFrame.setVisible(true);
}
class ExampleTableModel extends AbstractTableModel{
int laps = 0;
String lapTime;
double currentTime = 0;
String difference;
Trial t = new Trial();
//Two arrays used for the table data
private String[] columnNames = {"Lap #", "Total Time", "Lap Time" , "Difference" };
private Object[][] data;
public ExampleTableModel(){
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = t.getArray1() [i];
data[i][2] = t.getArray2()[i];
data[i][3] = t.getArray3()[i];
}
}
#Override public int getRowCount() {
return data.length;
}
#Override public int getColumnCount() {
return columnNames.length;
}
#Override public Object getValueAt(int row, int column) {
return data[row][column];
}
#Override public String getColumnName(int column) {
return columnNames[column];
}
#Override public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override public boolean isCellEditable(int row, int column) {
if (column == 0 || column == 1) {
return false;
}
else {
return true;
}
}
}
}
I made those changes but I need my output to look like this
Lap #: Total time Lap time Difference
Lap1: 2:10 2:10 ---
I fixed the lap number so it starts at 1. I made these changes in the hopes that it would fix the lap time and difference cells but it is giving me an error.
public ExampleTableModel(Trial trial){
int laps = trial.getLapsCount();
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
if (i == 0){
data[i][0] = "Lap " + (i + 1);
data[i][1] = trial.getArray1() [i + 1];
data[i][2] = trial.getArray2() [i + 1];
data[i][3] = trial.getDifference(i, (trial.getArray3()[i + 1] - trial.getArray3()[i]));
}
else {
data[i][0] = "Lap " + (i + 1);
data[i][1] = trial.getArray1() [i + 1];
data[i][2] = trial.displayTime(trial.getArray2() [i + 1] - trial.getArray2() [i]);
data[i][3] = trial.getDifference(i, (trial.getArray3()[i + 1] - trial.getArray3()[i])) + (trial.getArray3()[i + 1] - trial.getArray3()[i]);
}
}
}
Edit: combining the code from the Trial.main and the Table.main methods
To make the code from your Trial class easier to use from the Table class, you can make the following changes. This way you can create a Trial object and call the getUserInput to let the user initialize it:
public static void main(String[] args) {
new Trial().getUserInput();
}
public void getUserInput() {
// [Code from the old main method...]
// Use the fields of the class instead of local variables:
lapsCount = Integer.parseInt(lapsString);
array1 = new String[lapsCount+1];
array2 = new double[lapsCount+1];
array3 = new double[lapsCount+1];
// [Code from the old main method...]
}
Now you can modify the Table model like this:
public Table() {
// [...]
Trial trial = new Trial();
trial.getUserInput();
JTable table = new JTable(new ExampleTableModel(trial));
// [...]
}
And let the ExampleTableModel constructor use a trail parameter (the laps and t fields are no longer used):
public ExampleTableModel(Trial trial){
int laps = trial.getLapsCount();
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = trial.getArray1()[i];
data[i][2] = trial.getArray2()[i];
data[i][3] = trial.getArray3()[i];
}
}
There was also an issue with the getColumnClass method:
#Override public Class getColumnClass(int column) {
//return getValueAt(0, column).getClass();
return (column <= 1) ? String.class : Double.class;
}
Now the table looks like this:
The output was:
Number of laps = "2"
Lap 1 = "2:10"
result = 0, user pressed "Yes"
Lap 2 = "2:20"
result = 0, user pressed "Yes"
Old answer
There seem to be a few issues that prevent the table from being filled:
In the ExampleTableModel class the laps field should be something higher than zero (for the constructor to fill the data array):
class ExampleTableModel extends AbstractTableModel {
//int laps = 0;
int laps = 6;
In the constructor of the ExampleTableModel class:
public ExampleTableModel(){
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = t.getArray1()[i];
data[i][2] = t.getArray2()[i];
data[i][3] = t.getArray3()[i];
}
}
the calls to the t.getArray1, t.getArray2, and t.getArray3 methods return null. The Trial object appears to have no data yet.
Do you want your program to execute both the code of the Trial.main method and the Table.main method?

CircularQueue program is getting errors

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 ();
}
}

Unchecked or unsafe operations when compiled, exception when atempted to run

When I attempt to compile my code, this error occurs:
Note: GoFishEdited.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
When I tried to run it, this error message occurs:
Exception in thread "main" java.lang.NullPointerException
at Habitat.stockUp(Habitat.java:20)
at GoFishEdited.main(GoFishEdited.java:14)
I'm pretty sure the error is in the stoockUp method, but I don't understand what could be wrong with it.
Here is my code:
public class GoFishEdited {
public static void main(String[] args) {
System.out.println("\nProject 1, Stage 3\n");
int[] fishArray;
ArrayList<Fish> catchF = new ArrayList<Fish>();
Habitat h1 = new Habitat();
Habitat h2 = new Habitat();
fishArray = h1.stockUp();
System.out.println("Start with some weights:");
for (int i : fishArray) {
System.out.print(i + " ");
}
System.out.println("\n\nMake fish of those weights.\n");
Fish[] fishGroup = new Fish[fishArray.length]; // array of Fish
for (int i=0; i < fishArray.length; i++) {
fishGroup[i] = new Fish(fishArray[i]); // make fish
}
System.out.println("Fish are made. Now put them in a habitat:\n");
for (Fish f : fishGroup) {
h1.addFish(f);
}
System.out.println("\nAll in. The habitat displays them:\n");
h1.printFish();
System.out.println("\nMove some fish to the second habitat.\n");
for(Fish f : fishGroup){
h2.addFish(f);
}
System.out.println("\nPrint both habitats:\n");
h1.printFish();
h2.printFish();
System.out.println("\nCatch some fish.\n");
for(Fish f : fishGroup){
catchF = h1.catchFish(f);
}
}
}
And:
public class Habitat {
ArrayList<Fish> stringer = new ArrayList<Fish>();
int[] fishArr;
public int maxCount=25;
public int minCount=9;
public int maxWeight=10;
public int minWeight=1;
public int catchProbability=30; //0.3
public ArrayList<Fish> catches = new ArrayList<Fish>();
public int[] stockUp(){
int numofF = minCount + (int)(Math.random() * ((maxCount - minCount) + 1));
for(int i = 0; i<numofF; i++){
fishArr[i] = minWeight + (int)(Math.random() * ((maxWeight - minWeight) + 1));
}
return fishArr;
}
public Habitat(){
int[] hab;
}
public void addFish(Fish f) {
stringer.add(f);
}
public void removeFish(Fish f){
stringer.remove(f);
}
public void printFish(){
System.out.println(stringer);
}
public ArrayList catchFish(Fish f){
int caught = 0 + (int)(Math.random() * ((100 - 0) + 1));
if(caught < catchProbability){
catches.add(f);
stringer.remove(f);
}
return catches;
}
public void printGrid(int[][] twoD){
int i, j;
for ( i = 0 ; i < twoD.length ; i++ ){
for ( j = 0 ; j < twoD[i].length ; j++ ){
System.out.print( twoD[i][j] + " " );
}
System.out.println();
}
}
public void toGrid(String[] oneD){
int cols = (int) Math.floor(Math.sqrt(oneD.length));
int currentCol = 0;
for(String element : oneD) {
System.out.print(element + "\t");
if(currentCol >= cols) {
System.out.println("");
currentCol = 0;
}
else {
currentCol++;
}
}
}
}
I would appreciate an explanation, because I am thoroughly confused, and just want to see if it'll work properly.
The problem is that you never initialize fishArr in Habitat
And the unchecked operation warning might come from public ArrayList catchFish(Fish f){, you should parameterize your return type

Categories