unidimensional battleship game in Java - java

I'm a college student and a beginner Java developer. I got this assignment for which I need to simulate a unidimensional battleship game using strings. The rules given to me are as follows:
The board has to be 10 in length and 1 in height
The computer puts on the board one length-one-ship and one length-two- ship
The user has to repeatedly shoot in one of the 10 possible position
Computer will respond to every shot with "water", "hit", "sunk", "already hit"
When all the ships have sunk, the game ends with the computer that tells you how many shots were needed.
What I came up with until now:
Define a method String buildBoard() that returns a random string made of 7 characters "water"; 2 characters, which have to be next to each other, for the "no hit length-two-ship"; and 1 character for the "no hit length-one-ship"
Define a method boolean endGame(String s) that returns true if all the ships were sunk.
Define a method String manageShot(String s, int p) that, given a Board configuration and a shot in position p, prints out the outcome of the shot (as explained above), and returns the new Board configuration.
Finally, define a void main(String[] args) method that manages input, method calls and the final print.
Do you think it could work?
Hopefully I have explained it in an understandable way.
My problem is that I have absolutely no idea on how to generate a random String especially if I have to keep two characters next to each other. Can someone please explain me how to do it?
Can you have a look at my code and see if it's all right or if it can be simplified?
public class UnidimensionalBattleship {
/* x - miss (no ships here)
* . - sea (available for firing)
* s - enemy ship (available for firing)
* c - enemy ship (2 spaces, available for firing) */
public static String map() {
String sea = new String("..........");
int pos;
Random rnd = new Random();
pos = rnd.nextInt(sea.length());
sea = sea.substring(0, pos) + "s" + sea.substring(pos + 1);
int shipsSet = 0;
do {
if (sea.substring(pos).equals(".") && sea.substring(pos+1).equals(".")) { //pos available
sea.substring(pos).equals("cc");
shipsSet++;
}
}while(shipsSet < 2);
return sea;
}
public static String manageShot(String sea, int p) {
char outcome = sea.charAt(p);
switch(outcome) {
case '.': System.out.println("Miss");
sea=sea.substring(p, p) + "x" + sea.substring(p+1);
break;
case 's': System.out.println("Sunk!");
sea=sea.substring(p, p) + "x" + sea.substring(p+1);
break;
case 'c': System.out.println("Hit!");
sea=sea.substring(p, p) + "x" + sea.substring(p+1);
break;
case 'x': System.out.println("Already Hit");
break;
}
return sea;
}
public static boolean endGame(String sea) {
int i; //counter
i=0;
for (i=0; i<sea.length(); i++) {
if (sea.charAt(i)=='.'|| sea.charAt(i)=='x')
i++;
}
return true;
}

My problem is that I have absolutely no idea on how to generate a random String especially if I have to keep two characters next to each other. Can someone please explain me how to do it?
Since you need to do it in String, some simple String manipulation with String functions will work. In order for you to determine whether it is a "hit", a "sunk", a "miss", or already hit, you can have a set of predefined letters to represent each of those.
For example:
x - miss (no ships here)
. - sea (available for firing)
s - enemy ship (available for firing)
c - enemy ship (2 spaces, available for firing)
To generate a string with ships on random positions, there are many ways to do this. You can use a StringBuilder and concatenate the String or simply use a char array and convert it to string after positioning the ships:
char[] sea = new char[10];
for(int x=0; x<sea.length; x++)
sea[x] = '.'; //set everything as sea first
Random rnd = new Random();
sea[rnd.nextInt(sea.length)] = 's'; //sea ship at random position
If you have multiple types of ships, use a different symbol to identify them.
If you have more than one ship, use a loop to fill the sea:
int shipsSet = 0;
do
{
int pos = rnd.nextInt(sea.length);
if(sea[pos] == '.'){ //pos available
sea[pos] = 's';
shipsSet++;
}
}while(shipsSet < 2);
Converting char array to String:
String map = String.valueOf(sea);
Generating the outcome:
int attackPos = scn.nextInt();
char outcome = map.charAt(attackPos);
switch(outcome){
case '.': System.out.println("Miss");
//use substring to mark this spot as "X"
break;
case 's': System.out.println("Sunk!"); //ship 's' only takes 1 space
//use substring to mark this spot as "X"
break;
case 'c': System.out.println("Hit!"); //ship 'c' takes 2 spaces
//use substring to mark this spot as "X"
break;
case 'x': System.out.println("Already Hit");
break;
}
The above shall give you a very good idea where to start and how to implement your entire program. If you are not allowed to use char array, simply use StringBuilder. If it is also not allowed, just use substring to generate a map with ships on random positions.

I think I've got the first part with this - you can use RandomStringUtils from Apache Commons...
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html#random(int, java.lang.String)
As you can see, it takes an integer and a String - the Integer is the length of the string and the String is the group of characters it will use.
I will have a poke around in the internet to see if I can help you with keeping the two characters together.

Related

Using ASCII for board co-ordinates in Java

I'm pretty new to Java and learning it as a hobby mainly after school to kill my free time productively. I find it really interesting and picking it up relatively pain free however I'm a bit stuck trying to implement a basic chess program that can be played via the command line. Ideally, I'd like to print out the board initially with just Kings and Queens on both sides and get them moving forwards, backwards and diagonally. (Once I get the hang of this I would try adding all other pieces, but at first I would like to just start as simply as possible). For simplicity I will just be using the standard 8x8 playing board.
I've already created a main game loop which uses a command line input of 1 to switch players and 2 to exit the game but I am stuck when it comes to printing out positions and having them change during the game. Firstly I would like to print out the starting positions of both kings and queens as a string (e.g ["D1","E1","D8","E8"]) for the player to see. I imagine the best way to do this is by using the ASCII index but I'm not really sure where to go from this, I tried the code below I know it's not correct and I don't know what to change...
int num[] = {65, 66, 67, 68, 69, 70, 71, 72};
String start_Pos =null;
for(int i = 4; i < 6; i++){
start_Pos[i] = (Character.toString((char)i) + "1");
}
int num[] = {65, 66, 67, 68, 69, 70, 71, 72};
String start_Pos =null;
for(int i = 4; i < 6; i++){
start_Pos1[i] = (Character.toString((char)i) + "8");
}
System.out.println(start_Pos + start_Pos1);
I have also tried coding the board set-up but this is literally just printing out the starting positions of the pieces and therefore will not change when a player makes a move - ideally it should. An example would be the starting positions are shown on the board like so:
Photo (PS I know QK should be swapped on one side so they're not opposite each other, my bad!
But after an input of "D1 D3" (first coordinates indicating what piece and the second indicating final position)from player 1 the board changes to reflect this. Is this possible without having to recompile the entire code after each turn? (Maybe a stupid question...).
Any help would be greatly appreciated. I find learning through making small games like these a lot more interesting and rewarding so if anyone is able to help me implement this I would be very thankful.
Java is an Object Oriented language, so it is best to use classes and object instances.
Of course, with a chessboard, you'll still want to perform calculations on the x, y coordinates. Computers are just better with numbers, they have problems interpreting things. The chess notation is mainly of use to us humans.
So here is a class that can be used to parse and interpret chess positions. Note that you should keep this class immutable and simply use a new object instance rather than changing the x or y field.
public final class ChessPosition {
// use constants so you understand what the 8 is in your code
private static final int BOARD_SIZE = 8;
// zero based indices, to be used in a 2D array
private final int x;
private final int y;
public ChessPosition(int x, int y) {
// guards checks, so that the object doesn't enter an invalid state
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) {
throw new IllegalArgumentException("Invalid position");
}
this.x = x;
this.y = y;
}
public ChessPosition(String chessNotation) {
// accept upper and lowercase, but output only uppercase
String chessNotationUpper = chessNotation.toUpperCase();
// use a regular expression for this guard
if (!chessNotationUpper.matches("[A-H][0-7]")) {
throw new IllegalArgumentException("Invalid position");
}
// can be done in one statement, but we're not in a hurry
char xc = chessNotationUpper.charAt(0);
// chars are also numbers, so we can just use subtraction with another char
x = xc - 'A';
char yc = chessNotation.charAt(1);
// note that before calculation, they are converted to int by Java
y = yc - '1';
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public String getChessNotation() {
// perform the reverse and create a string out of it
// using StringBuilder#append(char c) is another option, but this is easier
return new String(new char[] {
// Java converts 'A' to int first (value 0x00000041)
(char) (x + 'A'),
(char) (y + '1')
});
}
// this will be helpfully displayed in your debugger, so implement toString()!
#Override
public String toString() {
return getChessNotation();
}
}
Now probably you want to also create a Board class with a backing 2D array of ChessPiece[][] and perform board.set(WHITE_KING, new ChessPosition("E1")) or something similar.

How would I ask java to stop until a variable is changed?

so I am trying to design a GUI with the program BlueJ, that sends data from a jtextfield box into a variable (already done), and using that variable to be able to update another variable, but for java to "stop running" until a specific variable is updated. So something along the lines of...
string bacon = "";
int agility = 1;
int dexterity = 2;
int strength = 3;
int intelligence = 4;
int charisma = 5;
//my variables.
if (bacon = "agility")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
agility= agility+bacon
}
else if (bacon = "dexterity")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
dexterity = dexterity+bacon
}
else if (bacon = "strength")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
strength = strength+bacon
}
else if (bacon = "intelligence")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
intelligence = intelligence+bacon
}
else if (bacon = "charisma")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
charisma = charisma+bacon
}
Thank you very much to anybody who can help me figure this out. I would also like it to have something so that if bacon is stated as a non-integer (32.7 or "hello"), it would simply ask you to input a proper integer.
Not quite sure what you are asking in the first part of the question, but for the second part to it check if it is a non integer you can do something like this....
boolean isValidInput = true;
for(int i=0;i<bacon.length();i++) {
char charAt = bacon.charAt(i);
if(!Character.isDigit(charAt)) {
isValidInput = false;
break;
}
}
if(!isValidInput)
System.out.println("Invalid Input!");
Also, = is used for assignment in java, ex a = 3;, however if you are trying to check if something is equal to something else, you should use the == operator. ex. if(x==2)
But in your case, since you are comparing Strings, you should use if(x.equals("hello"))
Another tip, instead of saying charisma = charisma + bacon; you can just say charisma += bacon; as a shorthand ;)
Hope this helps,
Saashin

Java - error: constructor "constructor name" in class "class name" cannot be applied to given types;

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 first post so please go easy on me if I did something wrong. Finally, I DO NOT want any specific solutions to my assignment in any responses to this post. Those issues are for me to figure out. What I do want is an explanation as to why my test code wont compile/run. To better understand the issue I will paste the assignment information, then the Driver class that is given, then my class code that is accessed by the Driver class. The compiler error I have is shown in the title, but since it is fairly vague, here is a screenshot of the exact errors I'm getting.
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
{
char[][] myHidingPlaces;
int myFloorLocation;
int myRoomLocation;
char myWinner;
boolean myFound;
Random random = new Random();
public void LostPuppy(int theFloors, int theRooms)
{// this ^ void is the issue and is now removed from my code(answered 7/14/2015 on stack overflow)
char[][] myHidingPlaces = new char[theFloors][theRooms];
for (int i = 0; i < theFloors; i++)
{
for (int j = 0; j < theRooms; 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)
{
if (myHidingPlaces[floor][room] == '1' ||
myHidingPlaces[floor][room] == '2')
{
return true;
}
else
{
return false;
}
}
public boolean puppyLocation(int floor, int room)
{
if (myHidingPlaces[floor][room] == 'P')
{
return true;
}
else
{
return false;
}
}
public boolean indicesOK(int floor, int room)
{
if (floor <= myHidingPlaces.length || room <= myHidingPlaces[0].length)
{
return true;
}
else
{
return false;
}
}
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 (myFound = true)
{
myWinner = player;
myFound = true;
return true;
}
else
{
myHidingPlaces[floor][room] = player;
return false;
}
}
public String toString()
{
return "this is a test";
}
}
I DO NOT want any specific solutions to my assignment in any responses
to this post. Those issues are for me to figure out. What I do want is
an explanation as to why my test code wont compile/run.
This line
game = new LostPuppy(totalFloors, totalRooms);
Won't compile because you haven't defined any constructor that expect two int as arguments (totalFloors and totalRooms).
In order to fix this, declare in your class LostPuppy a constructor such as
public LostPuppy(int totalFloors, int totalRooms)
{
//Do something here with paremeters..
}
This line
while (!game.indicesOK(floor, room)
Won't compile because you haven't defined any indicesOk method in your LostPuppy class.
Create a method such as
public boolean indicesOK(int floot, int room)
{
//return some conditions
}
I think your building method should be constructor:
public LostPuppy(int theFloors, int theRooms)
{
myHidingPlaces = new char[theFloors][theRooms]; //this line
for (int i = 0; i < theFloors; i++)
{
for (int j = 0; j < theRooms; j++)
{
myHidingPlaces[i][j] = ' ';
}
}
myFloorLocation = random.nextInt(theFloors);
myRoomLocation = random.nextInt(theRooms);
myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
myWinner = ' ';
myFound = false;
}
Note: look at the marked line, do not define type, if you define type, it becomes local variable instead of instance variable.

Calculate Dice Roll from Text Field

QUESTION:
How can I read the string "d6+2-d4" so that each d# will randomly generate a number within the parameter of the dice roll?
CLARIFIER:
I want to read a string and have it so when a d# appears, it will randomly generate a number such as to simulate a dice roll. Then, add up all the rolls and numbers to get a total. Much like how Roll20 does with their /roll command for an example. If !clarifying {lstThen.add("look at the Roll20 and play with the /roll command to understand it")} else if !understandStill {lstThen.add("I do not know what to say, someone else could try explaining it better...")}
Info:
I was making a Java program for Dungeons and Dragons, only to find that I have come across a problem in figuring out how to calculate the user input: I do not know how to evaluate a string such as this.
I theorize that I may need Java's eval at the end. I do know what I want to happen/have a theory on how to execute (this is more so PseudoCode than Java):
Random rand = new Random();
int i = 0;
String toEval;
String char;
String roll = txtField.getText();
while (i<roll.length) {
check if character at i position is a d, then highlight the numbers
after d until it comes to a special character/!aNumber
// so if d was found before 100, it will then highlight 100 and stop
// if the character is a symbol or the end of the string
if d appears {
char = rand.nextInt(#);
i + #'s of places;
// so when i++ occurs, it will move past whatever d# was in case
// d# was something like d100, d12, or d5291
} else {
char = roll.length[i];
}
toEval = toEval + char;
i++;
}
perform evaluation method on toEval to get a resulting number
list.add(roll + " = " + evaluated toEval);
EDIT:
With weston's help, I have honed in on what is likely needed, using a splitter with an array, it can detect certain symbols and add it into a list. However, it is my fault for not clarifying on what else was needed. The pseudocode above doesn't helpfully so this is what else I need to figure out.
roll.split("(+-/*^)");
As this part is what is also tripping me up. Should I make splits where there are numbers too? So an equation like:
String[] numbers = roll.split("(+-/*^)");
String[] symbols = roll.split("1234567890d")
// Rough idea for long way
loop statement {
loop to check for parentheses {
set operation to be done first
}
if symbol {
loop for symbol check {
perform operations
}}} // ending this since it looks like a bad way to do it...
// Better idea, originally thought up today (5/11/15)
int val[];
int re = 1;
loop {
if (list[i].containsIgnoreCase(d)) {
val[]=list[i].splitIgnoreCase("d");
list[i] = 0;
while (re <= val[0]) {
list[i] = list[i] + (rand.nextInt(val[1]) + 1);
re++;
}
}
}
// then create a string out of list[]/numbers[] and put together with
// symbols[] and use Java's evaluator for the String
wenton had it, it just seemed like it wasn't doing it for me (until I realised I wasn't specific on what I wanted) so basically to update, the string I want evaluated is (I know it's a little unorthodox, but it's to make a point; I also hope this clarifies even further of what is needed to make it work):
(3d12^d2-2)+d4(2*d4/d2)
From reading this, you may see the spots that I do not know how to perform very well... But that is why I am asking all you lovely, smart programmers out there! I hope I asked this clearly enough and thank you for your time :3
The trick with any programming problem is to break it up and write a method for each part, so below I have a method for rolling one dice, which is called by the one for rolling many.
private Random rand = new Random();
/**
* #param roll can be a multipart roll which is run and added up. e.g. d6+2-d4
*/
public int multiPartRoll(String roll) {
String[] parts = roll.split("(?=[+-])"); //split by +-, keeping them
int total = 0;
for (String partOfRoll : parts) { //roll each dice specified
total += singleRoll(partOfRoll);
}
return total;
}
/**
* #param roll can be fixed value, examples -1, +2, 15 or a dice to roll
* d6, +d20 -d100
*/
public int singleRoll(String roll) {
int di = roll.indexOf('d');
if (di == -1) //case where has no 'd'
return Integer.parseInt(roll);
int diceSize = Integer.parseInt(roll.substring(di + 1)); //value of string after 'd'
int result = rand.nextInt(diceSize) + 1; //roll the dice
if (roll.startsWith("-")) //negate if nessasary
result = -result;
return result;
}

Maintaining proper spacing in Java

I made a program that should output 2 lists of strings (anywhere between 2 and 5) at the end of the line, I want to print an int in brackets.
I am having trouble right justifying the int and the brackets.
All of the printf formatting does not help with moving the int and its surrounding brackets!
while (dealerPoints < 17 && playerBust == false) {
System.out.printf("\nDealer has less than 17. He hits...\n");
int nextDealerCard = dealCard();
dealerPoints += cardValue(nextDealerCard);
dealerHand += faceCard(nextDealerCard);
System.out.printf("Dealer: %s\t[%d]\n", dealerHand, dealerPoints);
System.out.printf("Player: %s\t[%d]\n", playerHand, playerPoints);
}
When there are 4 strings on one line and only 2 on the other, the int and brackets don't align with each other (the one after 4 strings, gets tabbed over too far)
System.out.printf("Dealer: %s\t[%10d]\n", "lala", 22222);
System.out.printf("Player: %s\t[%10d]\n", "hoho", 33);
Outputs:
Dealer: lala [ 22222]
Player: hoho [ 33]
is this what you want?
If you want to right justify, you can either
- write the output in a file as a CSV and open it in an excel like program
- create a utility class that will make any input string a constant length:
public static String fixedCharCount( String input, int length ) {
int spacesToAdd = length - input.lengh();
StringBuffer buff = new StringBuffer(input);
for( int i=0; i<spacesToAdd; i++) {
buff.append(" ");
}
return buff.toString();
}
You can also loop on all your data befor display to see what is the longest String in your table and adapt the length to it (the code is not complete: you must check 'spacesToAdd' is positive.

Categories

Resources