How would fill this array in this form? - java

I want my program to output this in a certain way, how would I make this possible? So far, my code is giving me the wrong thing.
Here's my .txt file:
ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO
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[6][5];
// fill array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
while(table[i][j] < 6) {
table[i][j] = line.charAt(j);
}
}
}
// print array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
System.out.println(table[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
How would I print this .txt file like so:
ABCDE
GHIJK
MNOPQ
STUVW
XYZOO
OOOOO

A couple of problems
see
String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
char[][] table = new char[6][5];
int counter = 0;
// fill array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
table[i][j] = line.charAt(counter++); // need to increment through the String
}
}
// print array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
System.out.print(table[i][j] + " "); // not println
}
System.out.println();
}
output
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 O O O O
Although a more extensible way would be link
String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
String lines [] = line.split("(?<=\\G.....)");
for (String l : lines) {
System.out.println(l);
}

Related

The code below reads from a text argument and displays an m x n matrice, I want to pass another text argument and compare it with the first 1

// here is a sample text file below board.txt
/* 4 4
x t x .
. . s .
x . . .
moves.txt lru
l for left, r for right u for up and d for down.
The first text file argument is a board game file on which s represents a start position and t the target.
and the second text file argument is a moves text file. I want to pass the second argument so that I can make those moves across the board file.
*/
public class VGame {
public static void main(String[] args) {
int m = StdIn.readInt();
int n = StdIn.readInt();
String[][] board1 = new String[m][n];
for (int i = 0; i < board1.length; i++) {
// the condition becomes false then gives access back to the outer for loop
for (int j = 0; j < board1[i].length; j++) {
board1[i][j] = StdIn.readString(); //reading from a text files
}
}
// now let's print a two dimensional array in Java for
/*for (char[] a : board1)
{
for (char i : a)
{
System.out.print(i + " ");
} System.out.println("\n");
} */
StdOut.println(m + " " + n);
for (int i = 0; i < board1.length; i++)
{
for (int j = 0; j < board1[i].length; j++)
{
System.out.print(" "+ board1[i][j]);
}
System.out.println();
}
// printing 2D array using Arrays.deepToString() method
//System.out.println("another way to print 2D arrays");
//System.out.println(Arrays.deepToString(board1));
StdOut.println(args[0]);
}
}
this should read the indexes as Integer and then the String line-by-line.
public class Main {
public static void main(String[] args) {
int m = 0;
int n = 0;
Scanner s = new Scanner(System.in);
System.out.print("input m: ");
m = s.nextInt();
System.out.print("input n: ");
n = s.nextInt();
String[][] board1 = new String[m][n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print("input string: ");
board1[i][j] = s.nextLine();
}
}
s.close();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.println(board1[i][j]);
}
}
}
}

Placing an array into a file column column

I currently have a .txt file with one line that looks like:
xxxxxxxxxxxxxxxxxxxxx
I would like to place that one line into a 2d array so my file can come out like so:
xxxxxxx
xxxxxxx
xxxxxxx
Here's my java class:
import java.util.*;
import java.io.*;
public class EncryptDecrypt {
public static void encrypt() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("TextFile.txt"));
String line = in.readLine();
String[][] e = new String[5][3];
// fill array
for(int i = 0; i < e.length; i++) {
for(int j = 0; j < e.length; j++) {
e[i][j] = line;
}
}
// print array
for(int i = 0; i < e.length; i++) {
for(int j = 0; j < e.length; j++) {
System.out.println(e[i][j]);
break;
}
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
When I run my java class, all I get is this which's not what I want:
xxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
You have to either use a 2D array of char or 1D array of String
'String' class is already internally implemented as an array of 'Char'.
Just use a 1D array of String, like:
String[] e = new String[3];
// fill array
for(int i = 0; i < e.length; i++) {
e[i] = line;
}
// print array
for(int i = 0; i < e.length; i++) {
System.out.println(e[i]);
}
The 2D version would be something like below (not recommended)
String line = in.readLine();
Char[][] e = new Char[3][5];
for(int i = 0; i < e.length; i++) {
for(int j = 0; j < e.length; j++) {
e[i][j] = line.charAt(j);//to access element at jth index of string
}
}
// print array
for(int i = 0; i < e.length; i++) {
for(int j = 0; j < e.length; j++) {
System.out.print(e[i][j]);
}
System.out.println()
}
Anyways for printing you do not to store in array, just do:
int noOfRows = 3;
for(int i=0;i<noOfRows;i++){
System.out.println(line)
}
You could just iterate over the string like this:
String line = "xxxxxxxxxxxxxxxxxxxxx";
int colums = 7;
for (int i = 0; i < line.length(); i++) {
System.out.print(line.charAt(i));
if ((i + 1) % colums == 0) {
System.out.println();
}
}
A more declarative version is possible when using Guava's Splitter:
for (String token : Splitter.fixedLength(coluns).split(line)) {
System.out.println(token);
}

Java 2D Array; Variable Row & Column Length from File Input

For this intro-level assignment, I have to set up a 2D multidimensional array from a file and from a double[][] a and apply several methods to them. For now, I'm mostly concerned with simply initializing the arrays. I'm trying to figure out a way to take a test file, read the first int as the number of rows, the first integer of each line as the number of columns per row, and each double as a member of the array.
public class MDArray
{
static int rowCount;
static int columnCount;
private static double[][] mdarray = new double[rowCount][columnCount];
public MDArray(double[][] a)
{
mdarray = a;
}
public MDArray(String file)
{
Scanner input = null;
try
{
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
System.exit(0);
}
while(input.hasNextDouble())
{
rowCount = input.nextInt();
for(int i = 0; i < rowCount; i++)
{
columnCount = input.nextInt();
for(int j = 0; j < columnCount; j++)
{
double value = input.nextDouble();
mdarray[i][j] = value;
}
}
}
}
public static boolean isRagged()
{
for(int i = 0; i < mdarray.length; i++)
{
int rowLength1 = mdarray.length;
for(int j = i + 1; j < mdarray.length; j++)
{
int rowLength2 = mdarray.length;
if(rowLength1 != rowLength2)
{
return true;
}
}
}
return false;
}
public static int getNumberOfRows()
{
int numRows = 0;
for(int i = 0; i < mdarray.length; i++)
{
numRows++;
}
return numRows;
}
public static int getNumberOfCols()
{
int numCols = 0;
for(int i = 0, j = i + 1; i < mdarray.length; i++)
{
for(int k = 0; k < mdarray[i].length; k++)
{
if(mdarray[i].length > mdarray[j].length)
{
numCols++;
}
}
}
return numCols;
}
public static double getValAt(int i, int j)
{
if(i > mdarray.length || j > mdarray[i].length)
{
double invalid = Double.NaN;
return invalid;
}
double valAt = mdarray[i][j];
return valAt;
}
public static void sort(boolean byColumn)
{
if(isRagged() == true)
{
System.out.println("Ragged arrays cannot be sorted by column.");
}
else{
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
for(int k = j + 1; k < mdarray[i].length; k++)
{
if(mdarray[i][j] < mdarray[i][k])
{
double temp = mdarray[i][j];
mdarray[i][k] = mdarray[i][j];
mdarray[i][j] = temp;
}
}
}
}
}
}
public static int hamming(boolean byColumn)
{
int hamVal = 0;
if(isRagged() == true)
{
System.out.println("Ragged arrays cannot be sorted by column.");
}
else{
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
for(int k = j + 1; k < mdarray[i].length; k++)
{
if(mdarray[i][j] < mdarray[i][k])
{
double temp = mdarray[i][j];
mdarray[i][k] = mdarray[i][j];
mdarray[i][j] = temp;
hamVal++;
}
}
}
}
}
return hamVal;
}
public static double[] max()
{
double[] maxVal = new double[mdarray.length];
for(int i = 0, j = i + 1; i < maxVal.length; i++)
{
for(int k = 0; k < mdarray[i].length; k++)
{
if(mdarray[i][k] > mdarray[j][k])
{
maxVal = mdarray[i];
}
}
}
return maxVal;
}
public String toString()
{
String arrayString = "";
for(int i = 0; i < mdarray.length; i++)
{
for(int j = 0; j < mdarray[i].length; j++)
{
arrayString += ", " + mdarray[i][j];
}
arrayString = arrayString + "/n";
}
return arrayString;
}
}
This was the file I was testing the MDArray(String file) with:
3
2 4.1 8.9
5 9.5 2.0 7.3 2.1 8.9
3 1.3 5.2 3.4
I think the problem is that the rowCount and columnCount integers are not initialized, but I'm not sure how to initialize them to a variable length with basic array skills. This is also affecting the other constructor as well. Being an intro-level course, I am not supposed to use more advanced techniques such as ArrayList. In addition, I can't verify if the methods are correct, since I don't have an array to test them with.
EDIT: While I did implement many of the suggestions in the answers, such as changing everything to non-static and other changes, I'm still getting a NullPointerException for the line mdarray[i][j] = input.nextDouble();. I assume it has to do with the private double[][] mdarray, which is required in the assignment specifications. Now I'm trying to find a way to initialize it such that it can be overridden in the later methods.
You have to initialize the array in your constructor, since that's when you know the dimensions :
public MDArray(String file)
{
Scanner input = null;
try {
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e) {
System.out.println("File Not Found.");
System.exit(0);
}
rowCount = input.nextInt();
mdarray = new double[rowCount][]; // init the array
for(int i = 0; i < rowCount; i++) {
columnCount = input.nextInt();
mdarray[i] = new double[columnCount]; // init the current row
for(int j = 0; j < columnCount; j++) {
mdarray[i][j] = input.nextDouble();
}
}
}
You could initialize your arrays by putting the amount of rows and columns on the first 2 lines of your multidimensional array, if i had 10 rows and 12 columns i could do something like this:
public void arrayStuff() {
File fileToRead = new File("YOUR LINK HERE");
String[][] data;
try (BufferedReader reader = new BufferedReader(new FileReader(fileToRead))) {
String line;
data = new String[Integer.parseInt(reader.readLine())][Integer.parseInt(reader.readLine())];
while((line = reader.readLine()) != null) {
// read the rest here..
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am using an AutoCloseable (which is why the try is between these ()'s, but this is so that i don't have to close it afterwards.
Basically, first i read the amount of rows there are and then the amount of columns there are, so if i had this file:
10
12
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
a b c d e f g h i j
It'd be able to read all of this, because the amount of rows and columns were defined in the file.
You don't use the fields rowCount and columnCount: you can remove them
The mdarray field should be non-static, so should be the methods that use them (if it was a utility class, you wouldn't have any constructor)
The arrays can be created while reading the file:
Scanner input = null;
try
{
input = new Scanner(new FileInputStream("ragged.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
System.exit(0);
}
int rowCount = input.nextInt();
mdarray = new double[rowCount][];
for(int i = 0; i < rowCount; i++)
{
int columnCount = input.nextInt();
mdarray[i] = new double[columnCount];
for(int j = 0; j < columnCount; j++)
{
double value = input.nextDouble();
mdarray[i][j] = value;
}
}
methods getNumberOfRows() and getNumberOfCols() count be much simpler:
public int getNumberOfRows()
{
return mdarray.length;
}
public int getNumberOfCols() {
int result = 0;
for (double[] col: mdarray) {
if (col.length > result) {
result = col.length;
}
}
return result;
}
In getValueAt(), the test is wrong; it should be:
if(i >= mdarray.length || j >= mdarray[i].length)

How to take String as input using Scanner, when input is of the form(below)?

Input:
abc
def
feg
cba
This is what I am doing, of course wrong!
import java.util.Scanner;
public class P {
public static void main(String []args){
Scanner x = new Scanner(System.in);
int t = x.nextInt();
for (int j=0; j<t; j++) {
String p[j] = x.nextLine();
}
for (j=0; j<p.length(); j++) {
for (k=0; k<p.length(); k++) {
if (p[j] = reverse(p[k])) {
int q = p[k].length();
System.out.println(""+q+((q/2)+1));
}
}
}
}
}
The error message you wrote is because of this code:
for (int j=0; j<t; j++) {
String p[j] = x.nextLine();
}
If you want to create a String array this is how you do it:
String[] p = new String[t];
It also needs to be declared outside of your for-loop. I suggest something like this:
public static void main(String []args){
Scanner x = new Scanner(System.in);
int t = x.nextInt();
String[] p = new String[t];
for (int j = 0; j < t; j++) {
p[j] = x.nextLine();
}
for (j=0; j<p.length(); j++) {
...
}
}
The new code you posted:
Scanner x = new Scanner(System.in);
int t = x.nextInt();
String p[] = new String[n];
for (int j = 0; j < t; j++) {
p[j] = x.nextLine();
}
for (j = 0; j < p.length(); j++) {
for(k = 1; k < p.length(); k++) {
if (p[j] = reverse(p[k])) {
int q = p[k].length();
System.out.println(""+q+((q/2)+1));
}
With all the corrections I've commented your code should look like this:
Scanner x = new Scanner(System.in);
int t = x.nextInt();
String[] p = new String[t];
for (int j = 0; j < t; j++) {
p[j] = x.nextLine();
}
for (int j = 0; j < p.length(); j++) {
for (int k = 1; k < p.length(); k++) {
if (p[j] = reverse(p[k])) {
int q = p[k].length();
System.out.println("" + q + ((q / 2) + 1));
}
}
}
at a glance, it seems like your scoping is off. The variable p in
for (int j=0; j<t; j++) {
String p[j] = x.nextLine();
}
is declared and then immediately discarded. You probably want something more like
String[] p = new String[t];
for (int j=0; j<t; j++) {
p[j] = x.nextLine();
}
similarly with q in the loop below
int q = 0;
for (int j=0; j<p.length; j++) {
for (int k=0; k<p.length; k++) {
if (p[j] = reverse(p[k])) {
q = p[k].length();
System.out.println(""+q+((q/2)+1));
}
}
}
Hope this helped.
more information about variable scope in Java:
variable scope

word search in java 2d array

I am trying to create a simple word search for a class assignment, and I have managed to figure out how to search east (from left to right) and west(right to left). But I am having trouble trying to figure out how to search south (top to bottom).
The code that I have works for one file that I read in but the second file returns an ArrayIndexOutOfBoundsException. Is there anything that is specific in my code that would make it un-scalable?
My corrected code looks like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import wordSeek.GameBoard;
public class WordGame {
private char[][] letters;
GameBoard gb;
public static void main(String[] args) {
WordGame wg = new WordGame();
wg.play();
}
public WordGame() {
letters = readLettersFromFile();
gb = new GameBoard(letters);
}
private void play() {
Scanner s = new Scanner(System.in);
String word;
do {
System.out.println("Enter word to find: ");
word = s.next();
// reset all highlighted tiles
gb.reset();
search(word);
} while (!word.equals("QUIT"));
gb.dispose();
}
// Nothing to be done above
// Complete all the methods below
private char[][] readLettersFromFile() {
// From the data in the file Letters.txt determine the size (number of
// rows and number of columns) for the letters array
int rowCount = 0;
int colCount = 0;
char c;
File file = new File("resources/Places.txt");
Scanner fileScanner = null;
try {
fileScanner = new Scanner(file);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> data = new ArrayList<String>();
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
data.add(line);
}
fileScanner.close();
rowCount = data.size();
colCount = data.get(0).trim().length()/2+1;
// Instantiate a two dimensional array of characters of the appropriate
// size
letters = new char [rowCount][colCount];
// Populate the array with the letters in Letters.txt
for (int i = 0; i < rowCount; i++) {
String line = data.get(i);
int pos = 0;
for (int j = 0; j < colCount; j++) {
letters[i][j] = line.charAt(pos);
pos += 2;
}
}
// return the array
return letters;
}
private void search(String word) {
System.out.println("Searching for " + word);
//Call the other search methods below as needed
searchIterativeEast(word);
searchIterativeWest(word);
searchIterativeSouth(word);
searchIterativeNorth(word);
}
//The following four methods must employ ITERATION to search the game board
private boolean searchIterativeEast(String word) {
int k = 0;
for (int i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters[i].length; j++) {
if (word.charAt(k) == letters[i][j]) {
k++;
}
else {
k = 0;
}
if (k == word.length()) {
for (int col = j - k + 1; col <= j; col++) {
gb.highlight(i, col);
}
return true;
}
}
}
return false;
}
private boolean searchIterativeWest(String word) {
String reversedWord = "";
for (int i = word.length() - 1; i != -1; i--)
{
reversedWord += word.charAt(i);
}
int k = 0;
for (int i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters[i].length; j++) {
if (reversedWord.charAt(k) == letters[i][j]) {
k++;
}
else {
k = 0;
}
if (k == reversedWord.length()) {
for (int col = j - k + 1; col <= j; col++) {
gb.highlight(i, col);
}
return true;
}
}
}
return false;
}
private boolean searchIterativeSouth(String word) {
int k = 0;
int store = letters[0].length;
for (int j = 0; j < letters[store].length; j++)
{
for (int i = 0; i < letters.length; i++)
{
if (word.charAt(k) == letters[i][j])
{
k++;
}
else
{
k = 0;
}
if (k == word.length())
{
for(int row = i-k+1 ; row <= i; row++)
{
gb.highlight(row, j);
}
return true;
}
}
}
return false;
}
private boolean searchIterativeNorth(String word) {
String reversedWord = "";
for (int i = word.length() - 1; i != -1; i--)
{
reversedWord += word.charAt(i);
}
int k = 0;
int store = 0;
for(int i = 0; i < letters.length; i++)
{
store = letters[i].length;
}
for (int j = 0; j < letters[store].length; j++)
{
for (int i = 0; i < letters.length; i++)
{
if (reversedWord.charAt(k) == letters[i][j])
{
k++;
}
else
{
k = 0;
}
if (k == reversedWord.length())
{
for(int row = i-k+1 ; row <= i; row++)
{
gb.highlight(row, j);
}
return true;
}
}
}
return false;
}
The Gameboard for the first file (Animals.txt) looks like: 5X4 2d Array
X C A T
P A L Q
I R B U
G P X N
G O D W
Output highlights CARP.
The Gameboard for the second file (Places.txt) looks like: 11x15 2d Array
O M J G D A X V C S Q N K I F
D A X V T Q O M J H A A H F C
A Y W U R P N L F E I T A L Y
J N H N E T H E R L A N D S F
D B I Z X V T O A R Q O A Y K
M K I A H F K R N O D B N N I
N Z Y W P H T V C G C T A A N
R A Q O T S N L E K K I C M G
I H P U U F D C A Z D O X R D
X W O A L E U Z E N E V N E O
V S U S J R Q L I Z A R B G M
The return statement goes outside of the for loop, otherwise you will only highlight the first letter.
...
for (int row = j-k+1; row <=i; row++ )
{
//gb.highlight() just calls a method that highlights the letters.
gb.highlight(row, j);
//return true;
}
return true;
...
for (int j = 0; j < letters[i].length; j++)
instead of
for (int j = 0; j < letters.length; j++)

Categories