I'm very curious about encryption so I went out and gave myself a little task, to encrypt a message (below in my .txt file). I'm not getting the output I want, I'm only getting the first column. Why's it only printing the first column?
Here's my java file:
import java.io.*;
public class EncryptDecrypt {
public static void encrypt() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("cryptographyTextFile.txt"));
String line = in.readLine();
char[][] table = new char[5][5];
// fill array
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table.length; j++) {
table[i][j] = line.charAt(j);
}
}
// print array
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table.length; j++) {
System.out.println(table[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
My .txt file contains:
E5NOWISTHEWINTEROFOURDISCONTENT*
My output is:
E
5
N
O
W
I want my output to be:
E I T W O O D
5 S H I F U I
N E N R S
O T C
W E O
R N
T
E
N
T
This part has an issue
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table.length; j++) {
table[i][j] = line.charAt(j);
}
}
You are only filling characters from j=0 to j=5 as your char array is of size 5 (you are retrieving first 5 characters of the line). I am unsure of what are you trying to achieve as a character array with 5X5 is not the answer.
If your txt file has line delimiters, you can make use of them and read each word into a string and have an array of strings.
I am leaving the explanation here as I couldn't make much out the question
That's because you are just iterating along the rows.
In the for loop, table.length moves along the rows (that is vertically), whereas table[0].length will iterate along the columns, that is on a single row (horizontally)
So you may want to change your loop to:
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
//your code here
}
}
Also, you need to have separate counter for your string. Your value of j is limited to the size of your array column length, namely from 0 to 4.
For idea, try this:
String line = in.readLine();
int cnt = 0;
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
while(cnt<line.length()){
table[i][j] = line.charAt(cnt);
cnt++;
}
}
}
Related
Just a simple question. I know to print all possible pairs, you do a nested for loop with a few more adjustments to be fancier. In my case, I want to take it a step up where pairs are not allowed to repeat or have 2 of the same integer in a pair.
For example: (0,0) is not allowed, but (0,1) is allowed. If (0,1) is a pair, then (1,0) is not allowed.
If I had integers "0,1,2,3", then my output would be
(0,0)(0,1)(0,2)(0,3)(1,2)(1,3)(2,3)
This is my current code that won't print pairs with 2 same integers, but repeated pairs still print.
for(int a = 0; a < 4;a++) {
numbers.add(a);
}
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(i != j) {
System.out.println("("+i+" , "+j+")");
}
}
}
Thanks
for(int i = 0; i < 4; i++) {
for(int j = i; j < 4; j++) {
if(i != j) {
System.out.println("("+i+" , "+j+")");
}
}
}
or
for(int i = 0; i < 4; i++) {
for(int j = i + 1; j < 4; j++) {
System.out.println("("+i+" , "+j+")");
}
}
I need to print this:
I need to print this square using a for loop in java.
This is what I have so far:
public static void main(String [] args)
{
for(int i = 0; i < 5; i++){
System.out.print("O ");
}
System.out.println();
for(int i = 0; i < 4; i++){
System.out.print("O ");
}
}
The easiest solution would be to nest two loops, first print O then use a second loop to print .. You know that each line should have a decreasing number of O (and increasing number of .s). In fact, you have 5 - i and i of each per line (where i is row number). And you can use the outer loop to determine how many of each should be drawn with those formulae. Like,
int size = 5;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size - i; j++) {
System.out.print("O ");
}
for (int j = 0; j < i; j++) {
System.out.print(". ");
}
System.out.println();
}
Which outputs (as requested)
O O O O O
O O O O .
O O O . .
O O . . .
O . . . .
Another option would be to create a StringBuilder to represent the initial conditions, print and then mutate the StringBuilder. This uses additional storage, but eliminates the need for nested loops.
int size = 5;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("O ");
}
for (int i = 0; i < size; i++) {
System.out.println(sb);
sb.setCharAt(sb.length() - (i * 2) - 2, '.');
}
And, you could also make that with an array of boolean(s) (e.g. a bitmask). Convert false to O and true to ., and set the last element offset by the index to true on each iteration. Like,
int size = 5;
boolean[] arr = new boolean[size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(arr[j] ? ". " : "O ");
}
System.out.println();
arr[size - i - 1] = true;
}
This is not a 'design pattern' problem. You just need to use the logic with loops.
Here's the logic.
In a square of n x n cells, the ith row contains (n-i) ovals and i
dots, where 0 <= i < n.
Refer to the other answer to see a working snippet.
Hi all my program consist of an 2 Dimension array,im reading 2 cordinates in a loop and triying to check if those cordinates in the array are alredy been filled with a asterisc,if this is true y want to re-enicialize my array with the default value "-", and if there is not an asterisc in that specified position y want to fill it in with a asterisc,im not sure if im going for the correct aproach.
this is part of my code.
thanks all.
String[][] matrix = new String[5][5];
String asterisc = "*";
String defaultValue = "_";
Scanner sc = new Scanner(System.in);
int a, b;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = defaultValue;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
System.out.print(matrix[i][j] + "|");
}
System.out.println();
}
a = 0;
b = 0;
while (a >= 0 && b >= 0 && a < matrix.length && b < matrix.length) {
a = sc.nextInt();
b = sc.nextInt();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[a][b].equals(asterisc)) {
matrix[i][j] = defaultValue;
} else {
matrix[a][b] = asterisc;
}
}
}
}
There are unfortunately many things wrong with your code.
Also you have not explained what your algorithm is trying to do.
In brief, to set all asterisks to defaults, you can do
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if matrix[i][j].equals(asterisc){
matrix[i][j]=defaultValue;
}
}
System.out.println();
}
But
why are you using a while loop?
Why are you using a scanner?
Why are a and b initialised at zero, yet need to be greater than zero for the loop?
Are you really trying to re-initialise your whole array, every time the (a,b) item is asterisc?
I think it is not true.Suppose you have typed "6 6" in the terminal,then the variable a=6,and b=6,which is greater than the array length,and the program will throw a exception.I think the thing you may want to do can follow this codeļ¼
while(true){
a = sc.nextInt();
b = sc.nextInt();
if(a<0||a>matrix.length||b<0||b>matrix.lenght)
break;
}
I have a String array like this
3
1 5 5
2 -2 -3
15 -100 20
how can i convert this to a 2d array
1 5 5
2 -2 -3
15 -100 20
3 is the size of 2d
public static class convert(String[] lines){
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 1; j < n; j++) {
String[] currentLine = lines[j].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j][i] = Integer.parseInt(currentLine[i]);
}
}
}
Sin,
You have a couple of Off-by-one errors.
Try this:
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 1; j <= n; j++) {
String[] currentLine = lines[j].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j-1][i] = Integer.parseInt(currentLine[i]);
}
}
Please let me know if you have any questions!
Since arrays are 0-indexed in Java, you should change your loop initialization variable j to start at 0.
Change:
for (int j = 1; j < n; j++) {
to
for (int j = 0; j < n; j++) {
Also, it seems you want a method to do the conversion, not a class so you should remove this from your method signature and put void since you aren't returning anything from the method.
Change:
public static class convert(String[] lines)
To:
public static void convert(String[] lines)
Also, you should use a different variable to iterate through the string array to make things more cleaner. Since you are trying to use j, you can do that to. Instead of initializing j to 1, you initialize it to 0 as I've said and use j+1 as the index for accessing the lines array.
Here is how your code could look like:
public static void convert(String[] lines)
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 0, k = 1; j < n; j++) {
String[] currentLine = lines[j + 1].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j][i] = Integer.parseInt(currentLine[i]);
}
}
}
I am using Java and working on 5X5 board game(represented as String[][]) and I looking for an efficient way to randomly place 3 "A"'s, 3 "B",s 3 "C"'s, 3 "D"'s on the board.
I thought about using a nested for loop inside of a while loop to go over each slot, and randomly assign letters to 'slots' on the board, but I want to possibly do it in one pass of the board, if there is a good way to randomly place all 15 letters on the board in one pass.
Any suggestions?
You can use an ArrayList to store the letters (and the empty cells, I'm using a dot . so you can recognize it in the output), then use Collections.shuffle() to put elements of the ArrayList in "random" places. Finally assign each letter to the String[][] array:
public static void main(String[] args)
{
String[][] board = new String[5][5];
List<String> letters = new ArrayList<>();
// fill with letters
for (int i = 0; i < 3; i++) {
letters.add("A");
letters.add("B");
letters.add("C");
letters.add("D");
letters.add("E");
}
// fill with "empty"
for (int i = 0; i < 10; i++) {
letters.add(".");
}
Collections.shuffle(letters);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
board[i][j] = letters.get(i*board.length + j);
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
Output Sample:
C B . . .
A E . E A
. A . D D
C . . . D
B C E . B
Note:
The operation i*board.length + j will generate consequent numbers 0, 1, 2, 3, ... 24 en the nested loop.
One way: create an ArrayList<Character> or of String, feed it the 15 letters, call java.util.Collections.shuffle(...) on the ArrayList, and then iterate over this List, placing its randomized items into your array.
e.g.,
List<String> stringList = new ArrayList<String>();
for (char c = 'A'; c <= 'E'; c++) {
for (int i = 0; i < 3; i++) {
stringList.add(String.valueOf(c));
}
}
for (int i = 15; i < 25; i++) {
stringList.add(null);
}
Collections.shuffle(stringList);
String[][] gameBoard = new String[5][5];
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
gameBoard[i][j] = stringList.get(i * gameBoard.length + j);
}
}
// now test it
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
System.out.printf("%-6s ", gameBoard[i][j]);
}
System.out.println();
}