Java - 2D Array Index Manipulation in a Complex Program - java

Before asking my question I want to make some things clear. First, I am new to Java and programming in general. Second, This is my second post so please go easy on me if I did something wrong. Finally, I would like an explanation as to why what I did was wrong instead of just a pasted solution in any responses to this post. To better understand the issue I will write the assignment information, then the Driver class that is given, then my class code that is accessed by the Driver class.
My question:
How can I get the bottom left of my 'building' to be [0][0] on my 2D array? Here's an example of a for loop that works in changing the bottom left of a 2D array to [0][0], but I tried implementing this into my searchRoom method (where the player character is set to myHidingPlaces index) and I can't get myHidingPlaces[0][0] to be the bottom left of my 2D Array. I believe that i need to edit the toString method somehow with for loops, but I can't figure out how I should do it.
The following is the assignment:
You are to design a class “LostPuppy.java” which represents a puppy lost in a multi-floor building that
contains the same number of rooms on each floor. During instantiation (or creation) of an object of this class,
each room on each floor will be initialized as empty (you will actually use the space ‘ ‘ character for this
purpose) and a random room will be chosen where the puppy is lost. For this purpose, the character “P” will
be placed in this random location. Further details on the constructor is listed below.
An object of this class is used as a game for two players to take turns searching for the puppy, one room at a
time until the unfortunate little canine is found. The instantiation of this object and the search will be performed
by a “driver” program which has been provided to you allowing you to only have to concentrate on developing
the class (the driver program is in the file “PuppyPlay.java”)
Fields (of course, all fields are private):
A character (char) array named myHidingPlaces. This represents the building where the rows are floors
and the columns are rooms on each floor (this building has an unusual numbering system; the floors and
rooms both start at zero).
Two integers that will hold the floor and room where the puppy is lost, named myFloorLocation and
myRoomLocation.
A char named myWinner which will be assigned the player’s character when a player finds the puppy
(the driver program uses digits ‘1’ and ‘2’ to more clearly distinguish the players from the puppy).
A boolean named myFound which is set to true when the puppy is found.
Constructor:
Receives two integer parameters as the user’s input for the number of floors and rooms of the building
in which the puppy is lost.
The constructor instantiates the 2D array “myHidingPlaces” as a character array with the first parameter
for the rows (theFloors) and the second parameter as the columns (theRooms).
Initialize myHidingPlaces’ cells, each to contain a space ‘ ‘ (done with single quotes)
Set myFloorLocation (floor puppy is on) randomly based using the first parameter
Set myRoomLocation (room puppy is in) randomly based using the second parameter
Set myHidingPlaces[myFloorLocation][myRoomLocation] to the char ‘P’
Set myWinner to a single space
Set myFound to false
Methods:
roomSearchedAlready receives the floor and room to be searched and returns true if the room has
already been searched, false otherwise.
puppyLocation receives the floor and room to be searched and returns true if the floor and room are
where the puppy is lost, false otherwise. This method should NOT change any of the fields.
indicesOK receives the floor and room to be searched and returns true if the floor and room values are
within the array indices range, false otherwise (used to check that these indices will not cause an error
when applied to the array).
numberOfFloors returns how many floors are in the building (the first floor starts at zero).
numberOfRooms returns how many rooms are on each floor of the building (the first room starts at
zero and all floors have the same number of rooms).
searchRoom receives the floor and room to be searched and also the current player (as a char type)
and returns true if the puppy is found, false otherwise. If the puppy is NOT found searchRoom also
sets the myHidingPlaces array at the received floor and room location to the received player value (a ‘1’
or a ‘2’) OR, when found, sets the myWinner field to the current player AND sets myFound to true.
toString displays the current hidingPlaces array and it’s contents EXCEPT the location of the puppy
which remains hidden until he/she is found at which point toString will be called (by the driver) and both
the player who found the puppy and a ‘P’ will be displayed in the same cell….
NOW, and perhaps the awkward portion of the toString output. Normally, when displaying a 2D array,
the [0][0] cell is displayed in the upper left corner as with matrices. However, because the puppy
decided to get lost in a building and not a matrix, it would make more visual sense to have the first floor
(row 0) displayed on the bottom, second floor above it… and finally the top floor, well… on top! To
save words, look closely at the sample run provided on the next page. Your output should look the
same as what is seen on the next page in the sample run.
Here is the Driver program:
import java.util.Random;
import java.util.Scanner;
/**
* This program is used as a driver program to play the game from the
* class LostPuppy. Not to be used for grading!
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
* #author David Schuessler
* #version Spring 2015
*/
public class PuppyPlay
{
/**
* Driver program to play LostPuppy.
*
* #param theArgs may contain file names in an array of type String
*/
public static void main(String[] theArgs)
{
Scanner s = new Scanner(System.in);
LostPuppy game;
int totalFloors;
int totalRooms;
int floor;
int room;
char[] players = {'1', '2'};
int playerIndex;
boolean found = false;
Random rand = new Random();
do
{
System.out.print("To find the puppy, we need to know:\n"
+ "\tHow many floors are in the building\n"
+ "\tHow many rooms are on the floors\n\n"
+ " Please enter the number of floors: ");
totalFloors = s.nextInt();
System.out.print("Please enter the number of rooms on the floors: ");
totalRooms = s.nextInt();
s.nextLine(); // Consume previous newline character
// Start the game: Create a LostPuppy object:
game = new LostPuppy(totalFloors, totalRooms);
// Pick starting player
playerIndex = rand.nextInt(2);
System.out.println("\nFloor and room numbers start at zero '0'");
do
{
do
{
System.out.println("\nPlayer " + players[playerIndex]
+ ", enter floor and room to search separated by a space: ");
floor = s.nextInt();
room = s.nextInt();
//for testing, use random generation of floor and room
//floor = rand.nextInt(totalFloors);
//room = rand.nextInt(totalRooms);
} while (!game.indicesOK(floor, room)
|| game.roomSearchedAlready(floor, room));
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
} while (!found);
playerIndex = (playerIndex + 1) % 2;
System.out.println("Great job player " + players[playerIndex] +"!");
System.out.println("Would you like to find another puppy [Y/N]? ");
}
while (s.nextLine().equalsIgnoreCase("Y"));
}
}
Finally, here is my test code:
import java.util.Random;
import java.util.Scanner;
public class LostPuppy
{
int value;
char[][] myHidingPlaces;
int myFloorLocation;
int myRoomLocation;
char myWinner;
boolean myFound;
Random random = new Random();
public LostPuppy(int theFloors, int theRooms)
{
myHidingPlaces = new char[theFloors][theRooms];
for (int i = theFloors - 1; i >= 0; i--)
{
for (int j = 0; j <= theRooms - 1; j++)
{
myHidingPlaces[i][j] = ' ';
}
}
myFloorLocation = random.nextInt(theFloors);
myRoomLocation = random.nextInt(theRooms);
myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
myWinner = ' ';
myFound = false;
}
public boolean roomSearchedAlready(int floor, int room)
{
return (myHidingPlaces[floor][room] == '1' ||
myHidingPlaces[floor][room] == '2');
}
public boolean puppyLocation(int floor, int room)
{
return (myHidingPlaces[floor][room] == 'P');
}
public boolean indicesOK(int floor, int room)
{
return (floor <= myHidingPlaces.length && room <= myHidingPlaces[0].length);
}
public int numberOfFloors()
{
return myHidingPlaces.length - 1;
}
public int numberOfRooms()
{
return myHidingPlaces[0].length - 1;
}
public boolean searchRoom(int floor, int room, char player)
{
if (puppyLocation(floor, room))
{
myFound = true;
myWinner = player;
return true;
}
else
{
myHidingPlaces[floor][room] = player;
return false;
}
}
public String toString()
{
int rooms = myHidingPlaces[0].length;
int floors = myHidingPlaces.length;
System.out.print(" ");
for (int x = 0; x < rooms; x++)
{
System.out.print("___");
}
for (int y = 0; y < rooms - 1; y++)
{
System.out.print("_");
}
System.out.print("\n");
for (int r = 0; r < floors; r++)
{
System.out.print("| ");
for (int c = 0; c < rooms; c++)
{
if (myHidingPlaces[r][c] == 'P' && myFound)
{
System.out.print("" + myWinner + "" + myHidingPlaces[r][c] + "| ");
}
else if (myHidingPlaces[r][c] == 'P' && !myFound)
{
System.out.print(" | ");
}
else
{
System.out.print(myHidingPlaces[r][c] + " | ");
}
//System.out.print(myHidingPlaces[r][c] + " | ");
}
System.out.print("\n");
for (int i = 0; i < rooms; i++)
{
System.out.print("|___");
}
System.out.print("|\n");
}
return "";
}
}

There is no way you can make a reversed array in Java, but you don't need it. You need to think of the building and operate with it just like you would do it with matrices. However you need to print it upside-down. Also there is no changing of position in array by the link you provided, it is just an array traversal from last index to first.
So you need to print array upside-down and this is pretty easy. You need to change one line in your toString method, change
for (int r = 0; r < floors; r++)
to
for (int r = floors - 1; r >= 0; r--)
And you will get correct result!
Also in this case you don't need to fill array from last to first (at least because you fill it with the same value), like you do
for (int i = theFloors - 1; i >= 0; i--) {
for (int j = 0; j <= theRooms - 1; j++) {
...
}
}
It will be better if you do it like this (just better to read your code)
for (int i = 0; i < theFloors; i++) {
for (int j = 0; j < theRooms; j++) {
...
}
}
As #Dante said you also need to correct indicesOK method because last index of array is its length - 1, so when you access myHidingPlaces.length or myHidingPlaces[i].length element the exception ArrayIndexOutOfBoundsException will be thrown.
public boolean indicesOK(int floor, int room) {
return (floor < myHidingPlaces.length && room < myHidingPlaces[0].length);
}

Related

Trying to make a chessboard that takes simple string inputs and stores them in Java

I am still new to Java and have been working with 2D arrays recently. What I am trying to do is make a simple 2D grid array of a Chessboard that has the arrays from a1 all the way to h8. The first thing I tried to do is convert the array [8][8] so that the first 8 was characters and the second 8 was integers. What I am currently trying to do is prompt the user and ask them which coordinate they would like to choose (from a1 all the way to h8). When they choose one of the coordinates, I would like them to enter a string (which in the future will be my chess pieces) that will be stored on the board, so that, when I use another class to print these strings, it'll give me an output like "a5 - Lemon (As im not checking to see if the chess piece is a valid piece yet) or "h2 - Queen".
So, to clarify, the program asks the user "Please enter a coordinate (e.g. a5)". "Now, Please enter a piece to be placed on that coordinate" Which then gets stored in that coordinate. When the user types, for example, "Done" I would like all the coordinates that have pieces on them to be revealed as well as what piece was put on them.
Code:
import java.util.Scanner;
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
int[][] grid = new int [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-g][1-8]");
};
// now we now that the input is valid
int col = (int)(input.charAt(0) - 'a');
int row = (int)(input.charAt(1) - '0');
}
}
}
I have used a while loop to continuously prompt the user until they give a correct coordinate, but Im not sure how to prompt the user to enter a piece that gets stored in that coordinate?
Any help would be appreciated!
First of all, in order to store the piece name with the coordinates, you will need a 2D array of strings instead of integers.
After changing that, you take the user input again and then save the coordinates with the piece and save it in the 2d array at said column and row.
Also, the row is retrieved from the character (a-b-c-etc..) and the column from the number and not the way around.
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-g][1-8]");
};
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
System.out.println(Arrays.deepToString(grid));
}
}

What is wrong with method findNumber which performs sequential search in an array to find an index

I am supposed to get an output which shows player's numbers with their walks, outs, and hits, which comes from a .txt file.
I did most of the programming but th output shows -1 for all the players.
Where is the problem ?
Is it the findNumber method?
Or other syntax errors?
public class Baseball8
{
// implementation of main program
public static void main(String[] args) throws FileNotFoundException
{
// 1) connect to input file
Scanner fin = new Scanner(new FileReader("baseball.txt"));
// objects used to store data
final int LIST_LENGTH = 20;
int number = 0, // number, hits, walks, outs
hits,
walks,
outs,
players,
index,
teamSize = 0;
// 2) output descriptive messages
System.out.println("This program tracks a baseball player's number "
+ "and their\nnumber of walks, runs and outs for "
+ "each game in a season.\n");
// 3) declare an array of LIST_LENGTH players
Player[] team = new Player[20];
// 3a) loop over the teamsize
for ( index=0; index<LIST_LENGTH; index++)
// 3b) instantiate the i'th team member
{
team[index] = new Player();
}
// 4) loop on end of file
while (fin.hasNext())
{
// 5) attempt to input the data for the next Player
number = fin.nextInt();
hits = fin.nextInt();
walks = fin.nextInt();
outs = fin.nextInt();
// 6) find the index of this Player's numbEr
number = findNumber(team, index, teamSize);
// 7) if player number is not in the list
if(number == -1 )
{ // 7a) set the Number field for team[teamSize]
team[teamSize].getNumber();
team[teamSize].setNumber(number);
// 7b) set the Hits field for team[teamSize]
team[teamSize].getHits();
team[teamSize].setHits(hits);
// 7c) set the Walks field for team[teamSize]
team[teamSize].getWalks();
team[teamSize].setWalks(walks);
// 7d) set the Outs filed for team[teamSize]
team[teamSize].getOuts();
team[teamSize].setOuts(outs);
// 7e) increase teamSize by 1
teamSize++;
} // 8) else player number is in the list
else
{
// 8a) update the Hits field for team[index]
team[index].setHits(hits + team[index].getHits());
// 8b) update the Walks field for team[index]
team[index].setWalks(walks + team[index].getWalks());
// 8c) update the Outs field for team[index]
team[index].setOuts(outs + team[index].getOuts());
}
}
// 9) display the results
displayArray(team, teamSize);
// 10) disconnect from input file
fin.close();
} // end of main
public static int findNumber(Player[] team, int index,int teamSize )
{ // 1) assume that this player_ number is not in the list
int Save = -1;
// 2) loop over the list length
for (int i=0; i< teamSize - 1; i++)
{
if (index == team[i].getNumber())
Save = i;
}
return Save;
// 3) exit the loop if the number is found
// 4) update the index on successful search
// 5) return either the found index or -1
}
public static void displayArray(Player [] team, int team_size)
{
// 1) display headins of colums
System.out.println("\n\nPlayer\tHits\tWalks\tOuts\n"
+ "------\t----\t-----\t----\n");
// 2) loop over team size
for (int i=0; i < team_size; i++)
{
// 3) display i'th player
System.out.println(team[i]);
}
}
} // end of the class
This is the Player Constructor:
Player()
{
Number= Hits= Walks= Outs = 0;
}
Player ( int Number, int Outs, int Walks, int Hits)
{
Number= Hits= Walks= Outs = 0;
}
By
output shows -1 for all the players.
I suppose you mean the number of all players has been set to -1?
The findNumber-function gives the index of the player with the number you've given as an argument right?? So if you would make the following call:
findNumber(team, 10, 20);
it means you are searching for the player with number 10 in the team-array and you specify that the team-array represents a team with 20 players. The result of this function will then be the index(place) of the player in the team-array.
Well the reason your code is failing is this fragment of code:
number = fin.nextInt();
hits = fin.nextInt();
walks = fin.nextInt();
outs = fin.nextInt();
// 6) find the index of this Player's numbEr
number = findNumber(team, index, teamSize);
// 7) if player number is not in the list
if(number == -1 )
...
You read the number of the player, his hits, walks and outs from the file (so far so good) but then you are searching for the player with the value of index as number and you are storing the index of that player (the result of the findNumber-function in your number-variable. So you replace the number you just read with the result of the findNumber function (that will always return -1 because you're looking for players with as number the value of the index that probably holds a number that doesn't exist in the team and never will because of this error). I don't think that's what you want...
What you probably want is to search the index of the player that has the number you just read from the file (stored in the number variable), store that index in the index variable and then check if that index, now in the index variable, is -1 (meaning, player with number number doesn't exist yet) or not. So the fragment above should be:
number = fin.nextInt();
hits = fin.nextInt();
walks = fin.nextInt();
outs = fin.nextInt();
// 6) find the index of this Player's numbEr
index = findNumber(team, number, teamSize);
// 7) if player number is not in the list
if(index == -1 )
...
I hope this helps!
In the code following this fragment you used your variables correctly.
Good luck!

Monty hall simulation not functioning as expected

import java.util.Scanner;
import static java.lang.System.*;
import static java.lang.Math.*;
import java.util.Random;
public class Montyhall
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of attempts:");
int attempts = keyboard.nextInt();/*Decide how many times you want this to
run. The larger the number, the more realistic an answer you will get.*/
int curtains[] = new int[3]; //like the game show, one of these will be a winner
Random rand = new Random(); /*sets the methods up with the same random seed, which
otherwise changes by the milisecond and could influence the response*/
withoutswitch(curtains, attempts, rand);
withswitch(curtains, attempts, rand);
}
public static void withoutswitch(int curtains[], int attempts, Random rand)
{
int nsCorrect=0;
for(int x=0; x < attempts; x++)
{
int winner = rand.nextInt(3);//Sets the winner to 1, leaving the other two at 0.
curtains[winner] = 1; //It then checks to see if they are the same,
int guess = rand.nextInt(3); //a 1/3 chance, roughly.
if(curtains[guess]==1){
nsCorrect++;
}
curtains[0]=0;
curtains[1]=0;
curtains[2]=0;
//the player never changes their decision, so it does not matter if a door is opened.
}
System.out.println("Number of successes with no switch: " + nsCorrect);
}
public static void withswitch(int curtains[], int attempts, Random rand)
{
int ysCorrect=0;
int goat = 0;
for(int x=0; x < attempts; x++)
{
int winner = rand.nextInt(3);
curtains[winner] = 1;
int guess = rand.nextInt(3);
goat = rand.nextInt(3);//one of the doors is opened
while(goat == winner || goat == guess)//the opened door is randomized until
goat = rand.nextInt(3); //it isn't the guess or the winner.
int guess2 = rand.nextInt(3);
while(guess2 == guess || guess2 == goat)
guess2 = rand.nextInt(3);//the second guess goes through a similar process
if(curtains[guess2]==1){
ysCorrect++;
}
curtains[0]=0;
curtains[1]=0;
curtains[2]=0;
}
System.out.println("Number of successes with a switch: " + ysCorrect);
}
}
Sorry it's a bit messy, I'm trying to get back into coding after almost a year hiatus. The first part functions as intended, returning roughly a 1/3 chance of success. The second, however, should be giving me a 2/3 chance, but I'm still getting roughly the same amount right with the switch as with no switch. I looked through the site, and mostly found things outside of Java that I'm not familiar with. This one was very similar, but no one seemed to actually help with the main issue.
What can I do to make the odds more realistic? Advice on cleaning up the code would be appreciated as well.
Edit:Code now functions, I'm now just trying to slim it down.
In your method withoutswitch you need to change
if(guess==1)
nsCorrect++;
to
if (curtains[guess] == 1)
nsCorrect++;
same as in the withswitch method. After each run of the for-loop you need to reset the curtains to 0. Otherwise the previous 1 will be in there and after a few runs the curtains will only contain 1s.
private static void resetCurtains(int[] curtains) {
for (int i = 0; i < curtains.length; i++) {
curtains[i] = 0;
}
}
Call that method after every run within the for-loop.
In addition, i would recommend using {} even if the statements are 1-liner:
if (curtrains[guess] == 1) {
nsCorrect++;
}
Both of your methods do not function as intended.
Your "withoutswitch" method only picks a random number from 0, 1, or 2, and adds to a counter when its 1. In other words, I can simplify your "withoutswitch" method to this:
public static void withoutswitch(int attempts, Random rand) {
int counter = 0;
for (int i = 0; i < attempts; i++) {
if (rand.nextInt(3) == 1) counter++;
}
System.out.println(counter);
}
Your "withswitch" method, believe it or not, does the exact same thing. You start guessing using one variable, then you completely disregard it and do it to a second variable, and check if that is 1. So, it produces the exact same results.
Both of your methods use the "curtains" array, but not correctly. The point of this problem is to put the car behind a random door every time, but you never set your array back to all zeros, and so, after a few runs, it becomes an array of all ones, which definitely isn't what you want.
Here is some pseudocode to help you get started:
number of switch wins = 0
number of stay wins = 0
scan in the number of attempts
loop through each attempt:
make an array {0, 0, 0}
pick a random number (0, 1, or 2), and set that array index to 1 (winning index)
pick a random number (0, 1, or 2), and set it to choice
pick a random number (0, 1, or 2), and set it to the shown door
loop while the door number isn't the choice number or the winning index:
pick a random number (0, 1, or 2) and set it to the shown door
increment stay wins if the choice is equal to the winning index
increment switch wins if (3 - choice - showndoor) is equal to the winning index
print stay wins and switch wins
Note: that last bit of logic determines the index of the switched door, since your only possible indices are 0, 1, and 2, (0 + 1 + 2 = 3), then 3 - the door you chose - the door you were shown = the last door.
Hope this helps!
I would back up and restructure the whole thing. One object for the game, two descendents, one of which simply picks a door, one of which picks and then switches.
I'm not entirely following your switch logic but it's definitely wrong. Monty's logic is if the prize is behind the player's door you open one randomly, otherwise you open one with the goat. Only a single random number is desirable.
Likewise, the player switches. There is only one curtain at this point, no random numbers are needed.
A rough stab at the logic (not Java, not the whole program):
MontyHaulGame
{
int[] Curtains = new int[3];
int Car = Random(3);
int Guess;
Pick();
if (Guess == Car) Wins++;
}
MontyHaulNoSwitch : MontyHaulGame
{
Pick()
{
Guess = Random(3);
}
}
MontyHaulSwitch : MontyHaulGame
{
Pick()
{
Guess = Random(3);
OpenOne();
Switch();
}
OpenOne()
{
if Guess == Car then
Repeat
Monty = Random(3);
Until Monty != Guess;
else
Monty = 1;
While (Monty == Guess) || (Monty == Car)
Monty++;
}
Switch()
{
NewGuess = 1;
While (NewGuess == Guess) || (NewGuess == Monty)
NewGuess++;
Guess == NewGuess;
}
}

JAVA: If/Else/For Methods?! WHAT?

I can't even do the basics. What am I doing wrong?
I need to:
Draw a "X" made up of stars (*). I must prompt for the width of the X in stars.
My requirements for this assignment is:
+1 - prompt for size of X
+4 - draw X of stars (receive +2 if can draw solid square of stars)
I'm using Eclipse by the way!
import java.util.Scanner;
/*
*
*
* Description: Draws a X.
*/
public class Tutorial1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i,j;
System.out.print("Enter size of box: 4 ");
int size = sc.nextInt();
for (i=0; i < size; i++)
{
for (j=0; j < size; j++)
{
if ( (i == 0) // First row
|| (i == size-1) // Last row
|| (j == 0) // First column
|| (j == size-1) ) // Last column
System.out.print("*"); // Draw star
else
System.out.print(" "); // Draw space
}
System.out.println();
}
}
} //
Your program draws a box correctly.
Enter size of box: 4 7
*******
* *
* *
* *
* *
* *
*******
You need to change your code so it draws a cross instead. The code is actually simpler as you have just two lines instead of four.
I would remove the 4 from the prompt as it confusing.
Enter size of box: 7
* *
* *
* *
*
* *
* *
* *
You already know you problem. You stated it yourself: "I can't even do the basics".
Then learn the basics. There is no way around THAT.
This site is not a "write me a piece of code that does X" service. People will help you only with specific questions on a specific problem. Your task is actually beginner stuff that is pretty simple once you grasped the basic concepts. Failing that, any solution we may provide here will be useless to you, since you don't even understand how the problem was solved. Worse, your teach will most likely notice pretty fast that you did not write that on your own. That screws you double - you get charged of cheating and still haven't learned anything.
Here is the skeleton of what you need. The for loops will iterate through the table. The hard part is coming up with the algorithm for deciding which character to print.
public class Tutorial1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i,j;
System.out.print("Enter size of box: ");
size = sc.nextInt();
Tutorial1 t = new Tutorial1();
t.printX(size);
}
private int _size = 0;
public void printX(int size) {
_size = size;
for(int row = 0; row < _size;row++) {
for(int col = 0; col< _size;col++) {
System.out.print(getChar(row,col));
}
System.out.println();
}
}
private String getChar(int row, int col) {
//TODO: create char algorithm
//As a pointer, think about the lines of the X independently and
//how they increment/decrement with the rows
}
}

How can i specify where o board ends?

i have a board([17][17]) and i place words in it giving the row and the column.I want if the position of the word given is bigger than the board,then a message is shown and you should give the row and column again.
**Board class**
......
public void placeWord(char[][] board, String word, int x, int y)
for (int i = 0; i < word.length(); i++)
{
if (y + i >= board[x].length)
{
System.out.println("The board is smaller!!");
Board b=new Board();
int a,r;
System.out.println("Give row and column again");
a=in.nextInt();
r=in.nextInt();
b.placeWord(board, word, a, r);
}
else {
board[x][y + i] = word.charAt(i);
}
}
When i give a=3 and r=5 it still prints me "The board is smaller!!" and want to give new values again.Does anyone know how to fix this?
Edit
**main()**
board b=new board();
String s="abc";
int x=2,y=20;
b.placeWord(Board, s, x, y);
for(int i=0;i<Board.length;i++)//prints the board
{
System.out.println(Board[i]);
}
From a=3 and r=5 I suspect you already failed for placing the word in the first place and entered a new row/column.
In this case the "old" for loop has not finished yet and will continue to place letters (as long as there are some remaining) after the call to b.placeWord(...);.
One way to circumvent this is to break the loop by a simple break; statement after the call to b.placeWord(...);.
Note: the second time you are filling the word into your newly created board b which you discard afterwards (it is never accessed anywhere in the code you showed us). Additionally you might first test if the word fits (can actually be done without a loop: y+word.length()<=board[x].length()) and then fill in the letters. Otherwise the remainders of the failed attempt will stay on the board.
**Board class**
......
public void placeWord(char[][] board, String word, int x, int y)
if (y + word.length() >= board[x].length)
{
// don't loop, ask for another position to put word
System.out.println("The board is smaller!!");
Board b=new Board();
int a,r;
System.out.println("Give row and column again");
a=in.nextInt();
r=in.nextInt();
b.placeWord(board, word, a, r);
} else
{
// already done the checking, don't need to worry here
for (int i = 0; i < word.length(); i++)
{
board[x][y + i] = word.charAt(i);
}
}

Categories

Resources