2d array gamemap line numbering - java

I'm trying to create a 2d gamefield with line numbering, but I can't get my head around how to code the numbering correctly in java.
What I have so far is only working up to an imput of rows and columns to 9.
For any two digit number or higher it's not displaying the map correctly as I don't have enough space. I could add to block let's say two blank spaces so the line numbering can go up to hundreds, but I'm trying to get a map that isn't restricted.
Any help is much appreciated.
Here is what I have now:
public String toString() {
String output;
output = "gamemap:\n ";
for (int j = 0; j < this.y; j++) { // loop over columns
output += j;
}
output += "\n *";
for (int j = 0; j < this.y; j++) { // loop over columns
output += "*";
}
output += "*\n";
for (int i = 0; i < this.x; i++) { // loop over rows
output += i + "*";
for (int j = 0; j < this.y; j++) { // loop over columns
output += this.map[i][j];
}
output += "*\n";
}
output += " *";
for (int j = 0; j < this.y; j++) { // loop over columns
output += "*";
}
output += "*\n";
output += "The player has "+ this.player.lives + " lives left.";
return output;
}

private String getPaddedNumber(int number, int maxNumber) {
if(maxNumber <= number) return Integer.toString(number);
int buffer = number;
while((buffer /= 10) != 0 & (maxNumber /= 10) != 0) {
//nothing
}
StringBuilder sb = new StringBuilder();
while(maxNumber != 0) {
sb.append('0'); //alternatively sb.append(' ');
maxNumber /= 10;
}
return sb.append(number).toString();
}
number is the line number you want to display, maxNumber would be the number of lines you have (or more precicely, the highest line index you have)

Related

I'm trying to make a Matrix from a 2D array but when I print it out its blank?

I'm currently making a program that take a phrase then runs it through 2 matrixs to encrypt it, I'm having trouble with the second matrix where I take a translation of the phrase eg.ADFGESZE and split it up and use the chars to populate the array but the problem the matrix always is blank when I print it and I dont know why as I've looked through my code afew time and cant find the problem and now im confused from pulling chunks of code from Stack Overflow to fix it, Ive posted it in pastebin if any of yous could spot the problem id appreciate it.
Where I get the translation:
package polycipher;
import java.util.Scanner;
public class Matrix {
private final char[] CIPHER_KEY = { 'A', 'D', 'F', 'G', 'V', 'X' }; // static morse array
private final String validChars = "ABCDEFGHIJ
KLMNOPQRSTUVWXYZ0123456789"; // characters which can be used
public String translation = ""; // for storing it the translation of the phrase
{ // failsafe, our program will be stuck in an infinite loop if
// number of valid characters is not at lease the square of CIPHER_KEY
if(validChars.length() < CIPHER_KEY.length*CIPHER_KEY.length) {
System.out.println("Error: Not enough valid characters to populate matrix.");
}
}
private char[][] matrix = new char[CIPHER_KEY.length][CIPHER_KEY.length]; // field for holding the generated matrix
private int[] usedNumbers = new int[validChars.length()]; // field for enforcing unique characters
{ // initiate all array elements to -1 (our "empty" value)
for (int x = 0; x < usedNumbers.length; x++)
usedNumbers[x] = -1;
}
public Matrix() { // Matrix default constructor override
int random;
for (int i = 0; i < CIPHER_KEY.length; i++) { // for every row
for (int j = 0; j < CIPHER_KEY.length; j++) { // for every column
validation: while (true) { // do this until I break the loop manually
random = (int) (Math.random() * validChars.length()); // generates a random number from 0 (inclusive) to (36 exclusive)
for (int k = 0; k < usedNumbers.length; k++) { // check every previously used character
if (random == usedNumbers[k]) {
continue validation; // if this char used before, skip it
} else if (usedNumbers[k] == -1) {
usedNumbers[k] = random; // if not previously used, store its value as used
break validation; // and break out of this validation loop
}
}
}
matrix[i][j] = validChars.split("")[random].charAt(0); // add this character to the matrix
}
}
}
public void searchMatrix(){
Scanner console = new Scanner (System.in);
String phrase ="";
System.out.println("\n Enter the message you would like "
+ "to encrypt with the cipher: ");
phrase = console.nextLine();
char[] phraseSplit = phrase.toUpperCase().toCharArray();
for (int k=0; k<phraseSplit.length; k++) {
for (int i=0; i<matrix.length; i++) {
for (int j=0; j<matrix[i].length; j++) {
if (phraseSplit[k] == matrix[i][j]) {
System.out.printf("%c has a Array Index %d, %d\n", phraseSplit[k], i, j);
if(i == 0){ translation += "A"; }
if(i == 1){ translation += "D"; }
if(i == 2){ translation += "F"; }
if(i == 3){ translation += "G"; }
if(i == 4){ translation += "V"; }
if(i == 5){ translation += "X"; }
if(j == 0){ translation += "A"; }
if(j == 1){ translation += "D"; }
if(j == 2){ translation += "F"; }
if(j == 3){ translation += "G"; }
if(j == 4){ translation += "V"; }
if(j == 5){ translation += "X"; }
}//end if
}//end for j
}//end for i
}//end for k
System.out.println("");
} //search end
public String toString() { // toString override, useful for debugging, prints out the matrix in a 6x6 table
String output = " A D F G V X\n";
for (int i = 0; i < CIPHER_KEY.length; i++) {
output += CIPHER_KEY[i] + " ";
for (int j = 0; j < CIPHER_KEY.length; j++) {
output += matrix[i][j] + " ";
}
output += "\n";
}
return output;
}
}
Where i populate and print the matrix:
package polycipher;
import java.util.*;
import polycipher.Matrix;
public class CipherKey {
Scanner write = new Scanner (System.in);
Matrix polyCipher = new Matrix();
private final char[] PHRASE_KEY = { 'J', 'A', 'V', 'A'};
String[][] matrixStore = new String[PHRASE_KEY.length][PHRASE_KEY.length];
public void assembleMatrix() {
polyCipher.translation = matrixFormatter(polyCipher.translation);
matrixStore = buildMatrix(polyCipher.translation,"|",",");
System.out.println(printMatrix(matrixStore));
}
public String printMatrix(String s [][]){
String keyOut = " J A V A\n";
for (int i = 0; i < s.length; i++) {
// keyOut += PHRASE_KEY[i] + " ";
for (int j = 0; j < s[i].length; j++) {
keyOut += s[i][j] + " ";
}
keyOut += "\n";
}
return keyOut;
}
public static String [][] buildMatrix (String translation, String outermarker, String innermarker) {
// outerdelim may be a group of characters
String [] sOuter = translation.split ("[" + outermarker + "]");
int size = sOuter.length;
// one dimension of the array has to be known on declaration:
String [][] result = new String [size][];
int count = 0;
for (String line : sOuter)
{
result [count] = line.split (innermarker);
++count;
}
return result;
}
public String matrixFormatter(String x){
String resultstr = "";
int i = 0;
while(i < x.length()) {
// If end of string: only add character.
if (i == x.length() - 1) {
resultstr += x.substring(i, i + 1);
} else {
if ( ((i + 1) % 4) == 0) {
resultstr += x.substring(i, i + 1) + "|";
} else {
resultstr += x.substring(i, i + 1) + ",";
}
}
i++;
}
return resultstr;
}
}
package polycipher;
/* This class will be for inplementing methods in the main and creating a GUI basically */
import polycipher.Matrix;
import polycipher.FileParsing;
import polycipher.CipherKey;
public class ApplicationDriver {
public static void main(String[] args) {
//Create and print the matrix
Matrix polyCipher = new Matrix();
System.out.print(polyCipher);
//Search the matrix with our message
polyCipher.searchMatrix();
System.out.println("Sting translated: " + polyCipher.translation);
System.out.println("Corordinates on Cipher: " +
java.util.Arrays.toString(polyCipher.translation.split("(?<=\\G..)")));
CipherKey Key = new CipherKey();
Key.assembleMatrix();
//Select our file
FileParsing secretFile = new FileParsing();
secretFile.openFile();
//Add the phrase to the file
secretFile.addPhrase(polyCipher.translation);
//Close the file
secretFile.closeFile();
}
}
Output:
A D F G V X
A B Q J 8 E R
D Z 0 L 6 5 9
F D 3 Y T I X
G C 4 O V W A
V F M N P K S
X U G H 1 7 2
Enter the message you would like to encrypt with the cipher:
gjhjkjvgjv
G has a Array Index 5, 1
J has a Array Index 0, 2
H has a Array Index 5, 2
J has a Array Index 0, 2
K has a Array Index 4, 4
J has a Array Index 0, 2
V has a Array Index 3, 3
G has a Array Index 5, 1
J has a Array Index 0, 2
V has a Array Index 3, 3
Sting translated: XDAFXFAFVVAFGGXDAFGG
Corordinates on Cipher: [XD, AF, XF, AF, VV, AF, GG, XD, AF, GG]
J A V A
Enter the .txt file you want to store your phrase in:
a matrix should appear below J A V A as the following:
J A V A
x x x x
x x x x
x x x x
eg.

Generating alphanumeric series

I am getting problem with generating a number based on the given number. Actually I had to get series like DAA001,DAA002,DAA003......DAA999 once DA series is filled with DAA999 it has to generate DAB001...DAB999 and once the series DAB is filled with DAB999 it has to generate DAC001 to DAC999 like that upto DAZ001 toDAZ999.
Here is my code please help me in this.
String start="DA";
String driv[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String PrNumber="";
int count=0;
if(driverprId<=999){
count=0;
start=start+driv[count];
if(driverprId>=1&&driverprId<10){
PrNumber=start+"00"+driverprId;
}
if(driverprId>=10&&driverprId<100){
PrNumber=start+"0"+driverprId;
}
if(driverprId>=100&&driverprId<=999){
PrNumber=start+driverprId;
}
}
if(driverprId>999){
}
return PrNumber;
Something like that should work:
String start="DA";
String driv[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(int i = 0; i < driv.length; i++) {
for(int j = 1; j <= 999; j++) {
String numbers;
if (j / 10 < 1) {
numbers = "00" + j;
} else if (j / 10 < 10) {
numbers = "0" + j;
} else {
numbers = "" + j;
}
PrNumber = start + driv[i] + numbers;
}
Condition only:
if (driverprId / 10 < 1) {
numbers = "00" + j;
} else if (driverprId / 10 < 10) {
numbers = "0" + j;
} else {
numbers = "" + j;
}
Try something like:
int counter = 0;
for (int i=0;i<driv.length;i++) {//for each alphabet
for (int j=0;j<999;j++) { //iterate till 999
start=start+driv[i];//keep using DA A if i is 0 for 999 times
...
if (counter == number) {//number is like number of cells you need
return;
}
counter++;
}
}

Nested For loops to print numbers 11223344556677889900

I am trying to print the sequence of numbers 11223344556677889900 using nested for loops. I am unsure of the algorithm to print the sequence since it ends in 00. I have the following method code but I print the 00 as literals and am sure that there must be a better way. Any help is much appreciated.
public static void drawNumbers(){
for (int line = 1; line <= 2; line++) {
for (int i =1; i <= 9; i++) {
for (int j =1; j<=2; j++) {
System.out.print(i);
}
}
System.out.print("00");
}
}
Run your loop up to 10 and instead of:
System.out.print(i);
do:
System.out.print(i % 10);
public static void drawNumbers(){
for (int line = 1; line <= 2; line++){
for (int i =1; i <= 10; i++){
for (int j =1; j<=2; j++){
System.out.print(i%10);
}
}
}
}
You can run the "i" loop until 10 and print i%10. This would print 0 when the value reaches 10.
One other way would be to insert an if statement inside the for where you would check if the value of i was equal to "10", and if it were, it would print the value "00"
Just only print the last digit of i
for (int i = 1; i <= 10; i++) {
String s = String.valueOf(i);
int lastDigit = s.length() - 1; // last digit position in string
System.out.print(s.substring(lastDigit, lastDigit + 1)); // print last digit
System.out.print(s.substring(lastDigit, lastDigit + 1)); // print last digit
}
Output:
11223344556677889900
Changed the logic a little to fit your requirement
public static void drawNumbers() {
for (int line = 1; line <= 1; line++) {
for (int i =1; i <= 10; i++) {
for (int j =1; j<=2; j++) {
if(i==10) {
System.out.print(0);
} else {
System.out.print(i);
}
}
}
}
}
To use only one loop run it like
public static void drawNumbers() {
for(int i = 1 ;i <= 10; i++) {
if(i ==10) {
System.out.print(0 + "" + 0);
} else {
System.out.print(i + "" + i);
}
}
}

Printing a diamond - can't enter input?

I'm trying to write a program that outputs a diamond pattern like this:
*
***
*****
***
*
I've started by trying to first get it to print the top half of the diamond.
I can input the 'totalLines' into the console, but I can't type anything when it prompts for 'character'. Why would this be happening?
We've been using JOptionPane for most of our assignments, so it makes sense that I'd be having trouble with this, but from what I can tell from reading the book, this is correct.
(And if you have time to talk to me about the for-loops, I'm pretty sure they need work. I'd be very grateful.)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int totalLines, lines, currLine = 1, spaces, maxSpaces, minSpaces, numCharacters, maxCharacters, minCharacters;
String character;
System.out.print("Enter the total number of lines: ");
totalLines = input.nextInt();
System.out.print("Enter the character to be used: ");
character = input.nextLine();
lines = ((totalLines + 1)/2);
// spaces = (Math.abs((totalLines + 1)/2)) - currLine;
maxSpaces = (totalLines + 1)/2 - 1;
minSpaces = 0;
// numCharacters = (totalLines - Math.abs((totalLines +1) - (2*currLine)));
maxCharacters = totalLines;
minCharacters = 1;
spaces = maxSpaces;
for (currLine = 1; currLine<=lines; currLine++) {
for (spaces = maxSpaces; spaces<=minSpaces; spaces--){
System.out.print(" ");
}
for (numCharacters = minCharacters; numCharacters>= maxCharacters; numCharacters++){
System.out.print(character);
System.out.print("\n");
}
}
}
Try using next() instead of nextLine().
I'm creating a separate answer in regards to your for loops. This should be pretty close to what you need.
StringBuilder might be new to you. Because StringBuilder is mutable and String is not, if you're doing multiple concatenations onto an existing string it's usually preferable to use StringBuilder instead of String. You don't have to use StringBuilder for this exercise but it's a good habit to start.
//Get user input here
int lines = totalLines;
if(totalLines % 2 != 0)
lines += 1;
int i, j, k;
for (i = lines; i > 0; i--)
{
StringBuilder spaces = new StringBuilder();
for (j = 1; j < i; j++)
{
spaces.append(" ");
}
if (lines >= j * 2)
{
System.out.print(spaces);
}
for(k = lines; k >= j * 2; k--)
{
System.out.print(character);
}
if (lines >= j * 2)
{
System.out.println();
}
}
for (i = 2; i <= lines; i++)
{
StringBuilder spaces = new StringBuilder();
System.out.print(" ");
for (j = 2; j < i; j++)
{
spaces.append(" ");
}
if(lines >= j * 2)
{
System.out.print(spaces);
}
for (k = lines ; k >= j * 2; k--)
{
System.out.print(character);
}
if (lines >= j * 2)
{
System.out.println();
}
}

Find the prime-->sieve way

I tried it several times but still gives me ArrayOutOfIndex. But i want to save the memory so i use
boolean[]isPrime = new boolean [N/2+1];
instead of
boolean[]isPrime = new boolean [N+1];
This gives me ArrayOutOfIndex for line 23 and 47
line 23:
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
line 47:
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
...
}
Full code:
public class PrimeSieve {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java PrimeSieve N [-s(ilent)]");
System.exit(0);
}
int N = Integer.parseInt(args[0]);
// initially assume all odd integers are prime
boolean[]isPrime = new boolean [N/2+1];
isPrime[2] = true;
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
int tripCount = 0;
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 3; i * i <= N; i=i+2) {
// if i is prime, then mark multiples of i as nonprime
if (isPrime[i]) {
int j = i * i;
while (j <= N){
tripCount++;
isPrime[j] = false;
j = j + 2*i;
}
}
}
System.out.println("Number of times in the inner loop: " + tripCount);
// count and display primes
int primes = 0;
if(N >= 2 ){
primes = 1;
}
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
if (args.length == 2 && args[1].equals("-s"))
; // do nothing
else
System.out.print(i + " ");
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
You should store and access the array using the same indexing function: isPrime[i/2]
When you change the size of your array from [N+1] to [N/2+1], you need to also update the end-conditions of your for-loops. Right now your for-loops run until i=N, so you are trying to do isPrime[i] when i > (N/2+1) ... so you get an ArrayIndexOutOfBoundsException.
Change this:
for (int i = 3; i <= N; i=i+2)
to this:
for (int i = 3; i <= N/2; i=i+2)
Well, for example if N=50 your isPrime only holds 26 elements, and you're trying to access the elements at 3,5..47,49 (which, of course, is out of bounds)
What you probably want is to use i/2 (as the index) inside your loops, that way you are still iterating over the numbers 3,5..47,49, but you use the correct indexes of your vector.

Categories

Resources