Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I shall program some methods in Java for the game battleship? Not sure how it's called in English.
We shall create the method:
private static Point[] createSchiff(int laenge)
Which creates a ship with the length laenge, a random position on the field and random direction, and returns a reference of the ship.
The ship shall be from the type Point and we shall use the object Vector as a container for all ships we create.
The full programmcode I have so far is:
import java.awt.*;
import java.awt.Point;
import java.lang.*;
import java.util.*;
public class Programm34 {
public int anzahlschiffe=5;
public Point[] schiffe = new Point[anzahlschiffe];
public static void main(String[]args){
Vector v=new Vector();
int i=10;
double random=0;
System.out.println("Zufallszahlen: ");
for(i=anzahlschiffe;i>0;i--){
random=random(0,10);
System.out.print((int)random+" ");
System.out.println("");
} //Test für random Methode!!
int[][] Spielfeld= new int[10][10];
init(Spielfeld);
for(int x=9;x>=0;x--){
for(int y=9;y>=0;y--){
System.out.print(Spielfeld[x][y]);
if(y!=0){
System.out.print(" ");
}
if(y==0 && x!=0){
System.out.print("\n");
}
}
}
}
private static long random(int u, int o){
double random;
random=Math.random()*(u-o)+o;
return (int)random;
}
private static Point[] createSchiff(int laenge){
point(1,2);
}
private static boolean positionOk(Vector<Point[]> schiffe,Point[] schiff){
}
private static boolean grenze(Point[] schiff){
}
private static boolean konflikt(Vector<Point[]> schiffe,Point[] schiff){
}
private static boolean nachbar(Vector<Point[]> schiffe,Point[] schiff){
}
private static boolean increment(Vector<Point[]> schiffe,int laenge){
}
private static void init(int[][] spielfeld){
for(int i=9;i>=0;i--){
for(int j=9;j>=0;j--){
spielfeld[i][j]=0;
}
}
}
private static void add(int[][] spielfeld, Vector<Point[]> schiffe){
}
}
All those methods and the main shall be programmed, but what matters ist the createschiff ("createship") one.
Can you help me explain the vector? the point? And how the whole stuff works? I sit here now for like 2 hours with no progress... thx alot
First a minor (but helpful) thing: You should add generics parameters to the vector. (I doubt that it is necessary to use Vector. A List should be sufficient. But when it is in the assignment, you have to do it...)
Vector<Point[]> v=new Vector<Point[]>();
About the createSchiff method: You' have to create several Point objects. Namely, one for each field that is covered by the ship. This could roughly look like this:
private static Point[] createSchiff(int laenge)
{
int positionX = ... // Some random position
int positionY = ... // Some random position
// Create the array that will contain the fields
// covered by the ship:
Point result[] = new Point[laenge];
// Fill the array
for (int i=0; i<laenge; i++)
{
result[i] = new Point(positionX, positionY);
// Change the position for the next field,
// depending on the direction of the ship:
positionX += ...
positionY += ...
}
return result;
}
Then you can call this method like this:
Point ship[] = createSchiff(3);
v.add(ship);
(I could insert more real code instead of the placeholders ... , but you should try this on your own)
Related
I'm trying to create a method which will create an object which contains a 2D boolean array, with int parameters as the number of rows and columns. Then inside the class, I have methods that try to grab the length and width of that array. The two ways I tried to solve this problem were:
public GameOfLife(int rows, int cols) {
boolean[][] society = new boolean[rows][cols];
}
public int numberOfRows() {
return society.length;
}
In my tests, this attempt was giving me the error that society cannot be resolved to a variable. Then I tried:
private boolean[][] society;
public GameOfLife(int rows, int cols) {
boolean[][] temp = new boolean[rows][cols];
society = temp;
}
EDIT: Oops, forgot to add my method for numberOfColumns:
public int numberOfColumns() {
return cols;
}
But the issue with this one was that it was returning 0 instead of 4 when I tried:
#Test
public void FailedTestingRowsAndCols(){
GameOfLife g1 = new GameOfLife(4,4);
assertEquals(4, g1.numberOfColumns());
}
I'm rather new to this, so I apologize if this is a dumb question, but I'm not really sure about all the details of where and when variables expire, which is giving me a lot of difficulties. THank you for any help!
When I create a 2D array outside of my constructor, I'm not able to resize it, but when I create one inside of it, I'm not able to access it
Take note that you will never be able to resize an array. An array once created has its size fixed. You are merely assigning your current array to reference to another newly created array (which gives you the illusion that you successfully resized it).
As for your question of not being able to access it is highly likely the variable you created exist within different scope.
You can use the following codes (which is very similar to yours), it works fine for me. Hence I am guessing your error does not actually comes from the code snippet you showed.
class TestRunner
{
public static void main(String[] args){
GameOfLife gol = new GameOfLife(5, 3);
System.out.println(gol.getColumns());
System.out.println(gol.getRows());
}
}
class GameOfLife
{
private boolean[][] society;
public GameOfLife(int rows, int cols){
society = new boolean[rows][cols];
}
public int getColumns(){
return society[0].length;
}
public int getRows(){
return society.length;
}
}
Output:
5
3
I don't see any problems with what you have posted so far. The below example works fine for me:
public class GameOfLife {
public static void main(String[] args) {
GameOfLife g1 = new GameOfLife(4,4);
System.out.println(g1);
}
private boolean[][] society;
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("GameOfLife{");
sb.append("society=").append(society == null ? "null" : Arrays.deepToString(society));
sb.append('}');
return sb.toString();
}
public GameOfLife(int rows, int cols) {
boolean[][] temp = new boolean[rows][cols];
society = temp;
}
}
I am EXTREMELY new to Java and completely lost on the concept of ARRAYS. I need to create a "World" class to display a two dimensional array that is user specified in size, using a constructor that accepts two values [rows] and [columns] with a character (Lets say "P") located in the array. A separate "Driver" class will hold the main method. Other methods (moveUp, moveDown, moveLeft, and moveRight) need to be created to move the character around inside the array. There needs to be a fifth method to display the world array. I currently have the following code, but nothing is working so I got rid of it. even this code itself won't compile - says "identifier expected before the parenthesis of my second println. I have no idea why this won't go any further. This is the only place I have to seek help since the college offers no tutors for Java, youtube videos are extremely vague and use terminology I do not know, library books I've checked out don't show me the actual code needed to perform these tasks, and the class textbook shows code close, but not quite what is needed. and since I'm extremely new to Java, my last questions garnered me the threat of losing the ability to post on this site, so that would take away my only recourse for help if this is also dubbed inferior. I do not know what to do at this point.
import java.util.*;
public class World
{
public static void main(String[] args)
{
System.out.println(array);
}
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
private int crow = input.nextInt();
System.out.println("Enter number of columns: ");
private int ccol = input.nextInt();
private String[][] array = newString[crow][ccol];
public int displayWorld()
{
}
public int moveUp()
{
}
public int moveDown()
{
}
public int moveLeft()
{
}
public int moveRight()
{
}
}
Compling problems-> use an IDE (eclipse netbeans idea jdeveloper ...) for developing java applications.
Here you have part of one solution, since you are learning, play with this code before implementing the rest of methods.
Regarding java learning, there are plenty of good tutorials by searching on google.
import java.util.*;
public class World{
private static final String P="P";
private String[][] array;
public World(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
int crow = input.nextInt();
System.out.println("Enter number of columns: ");
int ccol = input.nextInt();
array = new String[crow][ccol];
array[0][0]=P;
}
public void displayWorld(){
System.out.println();
for(int i=0;i<array.length;i++){
for (int j=0;j<array[i].length;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
public void moveUp(){
}
public void moveDown(){
for(int i=0;i<array.length;i++){
for (int j=0;j<array[i].length;j++){
if ((array[i][j])!=null){
if (i<array.length-1){
array[i][j]=null;
array[i+1][j]=P;
}
return;
}
}
}
}
public void moveLeft(){
}
public void moveRight(){
}
public static void main(String[] args){
World world=new World();
world.displayWorld();
world.moveDown();
world.displayWorld();
}
}
I'm new to Java, and need help. I have been asked to write a program that rolls dice and determines the chance of the player to get two "1s" on the top face of the dice. I have different functions such as role(), getTopFace() etc. I want to be get what the number on the dice is using these functions, but don't know how to call them in my main function. Here's my code:
import javax.swing.JOptionPane;
import java.util.Random;
public class SnakeEyes {
private final int sides;
private int topFace;
public static void main(String[]args)
{
String numberSides;
int n;
numberSides=JOptionPane.showInputDialog("Please enter the number of sides on the dice:");
n = Integer.parseInt ( numberSides);
int[]die=new int[n];
for (int index=0; index<n;index++)
{
die[index]=index+1;
}
//Here is where I want to get information from my functions and calculate the ods of getting two 1's.
}
public void Die(int n)
{
if(n>0)
{
int sides=n;
topFace=(int)(Math.random()*sides)+1;
}
else{
JOptionPane.showMessageDialog(null, " Die : precondition voliated");
}
}
public int getTopFace(int topFace)
{
return topFace;
}
public int role(int[] die)
{
topFace=(int)(Math.random()*sides)+1;
return topFace;
}
}
Make an object of your class SnakeEyes in your main method, and call the required functions using that object.
Example:
SnakeEyes diceObj = new SnakeEyes();
int topFace = diceObj.role(n,....);
If you want to call this functions from main this functions must be "static", because main its a static function and static function can only call other static functions.
But... this is a very ugly design for a java program, before jumping to write java code you need to understand at least a little about object orientation. For example, why you can't call a non-static function from a static function?, the answer of this question requires knowledge about object orientation and its a knowledge you need if you want to write serious java code.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am working with an ArrayList of objects that contain multiple variables. For example:
// pseudo code
class Ticket {
int gameID
double price
int seatnumber
}
and I have an ArrayList of multiple Ticket objects and need to access them. I've looked at the javadoc and so far I have come up with
list.get(index).attribute
However I get a compile-error saying:
cannot find symbol
am I doing something wrong with the syntax?
here is my code:
public static void printGameMoney(ArrayList games, ArrayList tickets)
{
double total = 0;
double tickMoney = 0;
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = tickets.get(i).priceOfTick;
total = total + tickMoney;
}
}
You code is "old-school", you should use typed-types, interfaces and new style for-loop:
public static void printGameMoney(final List<Game> games, final List<Ticket> tickets)
{
double total = 0;
for (final Ticket ticket : tickets)
{
final double tickMoney = ticket.getPriceOfTick();
total = total + tickMoney;
}
}
Also note this method is strange as it doesn't return anything.
If attribute is really one of your class member then please use as follow.
((Ticket) list.get(index)).attribute;
Start by putting semicolons after each field declaration:
class Ticket {
int gameID;
double price;
int seatnumber;
}
Also, show the exact code you're using instead of list.get(index).attribute.
List<Object> list = new ArrayList<Object>();
((Ticket)list.get(x)).attribute;
Use this instead:
public static void printGameMoney(ArrayList games, ArrayList<Ticket> tickets)
{
double total = 0;
double tickMoney = 0;
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = tickets.get(i).priceOfTick;
total = total + tickMoney;
}
}
Basically, the change leads to ArrayList<Ticket> instead of simple ArrayList. This way you tell the compiler that objects inside your ArrayList are of Ticket type, therefore they have attributes you specified (e.g. priceOfTick).
Same goes for games, so if you have Game class, you should use ArrayList<Game> games.
You have to access like this ,list.get(i).price; not list.price.get(i);
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = list.get(i).price;
total = total + tickMoney;
}
Here problem is that with your deceleration of ArrayList
If you declare like ArrayList<Ticket> you need not to cast there while getting. Other wise you need a cast there. More over use for each loop.
I'm learning about constructors.
When I try to compile the following code, I get the error "variable input and shape are not initialized."
Could anyone tell me why and how to solve it?
public class Try {
public static void main(String[] args)
{
String input;//user key in the height and width
int shape;//triangle or square
Count gen = new Count(input , shape);//is this the right way to code?
gen.solve();
}
}
public class Count {
public Count(String inp, int shp) {
String input_value = inp;
shape_type = shp;
}
public void solve () {
if shape_type==3{
//count the triangle
}
else if shape_type==4{
//count the square
}
}
}
You haven't given shape or input values yet before you try using them. Either you can give them dummy values for now, like
String input = "test";
int shape = 3;
Or get the string and integer from the user; in that case, you might want to take a look at how to use a Scanner.
By leaving input and shape without values, at:
String input;
int shape;
they are uninitialized, so Java doesn't know what their values really are.
I assume this is some kind of homework. I took the liberty of reformating and fixing your code a little.
You have to initialize any variable you are going to use. The only exception is when you are using class members (those are initialized automatically to some default value). See below that the members of the Count class aren't explicitly initialized.
This is some working code. Also note that i change the solve method a little (the if blocks should have had () around the expression. But what you are trying to do is usually better done with a switch block as shown below. Also I declared two members inside the Count class to remember the values provided at construction time in order to be able to use them when calling the solve() method.
public class Try {
public static void main(String[] args) {
String input = null; //user key in the height and width
int shape = 0; //triangle or square
Count gen = new Count(input, shape);//is this the right way to code?
gen.solve();
}
}
class Count {
String input_value;
int shape_type;
public Count(String inp, int shp) {
this.input_value = inp;
this.shape_type = shp;
}
public void solve() {
switch (this.shape_type) {
case 3:
// count the triangle
break;
case 4:
// count the square
break;
}
}
}
Proper formatting of the code usually helps :).