How to delete spaces In an 2D-Array in Java? - java

I have a text file. I am reading it then placing it into a 2D-Array. There are spaces. I need to get rid of those spaces. But I can't use trim properly. Here is my code:
while ((line = br.readLine() ) != null ){
char[] row = line.toCharArray();
line.trim();
int counter = 0;
for (int i = 0; i < row.length; i++) {
maze[counter][i] = row[i];
System.out.print(maze[i]);
counter++;
}
System.out.printf("%n");
}
The output is as follows:
1 1 1 0
0 0 1 0
0 0 1 0
0 9 1 0
The elements in the text file I read has one space between each other. But I get too many spaces as output. I need to get this as
1110
0010
0010
0910
I think I should use trim method, but I could not figure it out.

You can use String#split with a regular expression of something like \s+, for example...
String text = "1 1 1 0";
String elements[] = text.split("\\s+");
for (String value : elements) {
System.out.println("[" + value + "]");
}
Which outputs
[1]
[1]
[1]
[0]
(The braces are there to demonstrate that no spaces remain)
In your example I might still be tempted to still us line = line.trim(); to ensure that there are no leading or trailing space which might cause empty values to be included...

You can use (string).replace(" ", '\0') to replace all spaces with blanks
For example:
String line = "1 2 2 3 4 2 122 23 3 3 3 3"; //example
line = line.replace(' ', '\0'); //'\0' is the key for blank (or nothing)
System.out.println(line);
will produce
122342122233333
This will get rid of the spaces and only use the valid input (i.e. the numbers). It says row, but the only input will be the same characters.
Hope this helps.

Quickest way for me would be to just use a nested loop to print each element of the array individually. E.g.
String [][] maze = new String [4][4];
for (int i = 0; i < maze.length; i++) {
maze[i][0] = "1";
maze[i][1] = "0";
maze[i][2] = "1";
maze[i][3] = "0";
}
for (int k =0;k<maze.length;++k){
for(int j=0;j<maze.length;++j)
{
System.out.print(maze[k][j]);
}
System.out.println();
}

Related

Maximum repeating sequence instead of longest repeating sequence

I am trying to get the most repeated sequence of characters in a string.
For example :
Input:
s = "abccbaabccba"
Output:
2
I have used dynamic programming to figure out the repeating sequence, but this returns the longest repeating character sequence. For example:
Input:
s = "abcabcabcabc"
Output:
2
2(abcabc,abcabc) instead of 4(abc,abc,abc,abc)
Here is the part of the code where I'm filling the DP table and extracting repeating sequence. Can anyone suggest how I can get the most repeating sequence?
//Run through the string and fill the DP table.
char[] chars = s.toCharArray();
for(int i = 1; i <= length; i++){
for(int j = 1; j <= length; j++){
if( chars[i-1] == chars[j-1] && Math.abs(i-j) > table[i-1][j-1]){
table[i][j] = table[i-1][j-1] + 1;
if(table[i][j] > max_length_sub){
max_length_sub = table[i][j];
array_index = Math.min(i, j);
}
}else{
table[i][j] = 0;
}
}
}
//Check if there was a repeating sequence and return the number of times it occurred.
if( max_length_sub > 0 ){
String temp = s;
String subSeq = "";
for(int i = (array_index - max_length_sub); i< max_length_sub; i++){
subSeq = subSeq + s.charAt(i);
}
System.out.println( subSeq );
Pattern pattern = Pattern.compile(subSeq);
Matcher matcher = pattern.matcher(s);
int count = 0;
while (matcher.find())
count++;
// To find left overs - doesn't seem to matter
String[] splits = temp.split(subSeq);
if (splits.length == 0){
return count;
}else{
return 0;
}
}
Simple and dump, the the smallest sequence to be considered is a pair of characters (*):
loop over the whole String an get every consecutive pair of characters, like using a for and substring to get the characters;
count the occurrence of that pair in the String, create a method countOccurrences() using indexof(String, int) or regular expressions; and
store the greatest count, use one variable maxCount outside the loop and an if to check if the actual count is greater (or Math.max())
(*) if "abc" occurs 5 times, than "ab" (and "bc") will occur at least 5 times too - so it is enough to search just for "ab" and "bc", not need to check "abc"
Edit without leftovers, see comments, summary:
check if the first character is repeated over the whole string, if not
check if the 2 initial characters are repeated all over, if not
check if the 3 ...
at least 2 counters/loops needed: one for the number of characters to test, second for the position being tested. Some arithmetic could be used to improve performance: the length of the string must be divisible by the number of repeated characters without remainder.

String.split replication: OutOfBoundsException

For my CompSci class, we're making a Would You Rather? function for our chatbot project. The String.split() method works well for this, but we get bonus points if we can do it without it. I decided to go about this by just creating a method that replicated String.split.
private String[] separate (String phrase, String omit1, String omit2)
{
int c = 0;
//gets rid of leading and trailing whitespace, replaces target characters
//with the # character
phrase = phrase.trim();
phrase = phrase.replace(omit1, "#");
phrase = phrase.replace(omit2, "#");
//detects the number of phrases to be included in the array
for (int i = 0; i < phrase.length(); i++)
if (phrase.charAt(i) == '#')
c++;
//creates array list based on number of phrases
String[] phraseList = new String[c];
c = 0;
//builds phrases from characters found between occurrences
//of the # character
for (int i = 0; i < phrase.length(); i++)
{
if (phrase.charAt(i) == '#')
c++;
else if (phrase.charAt(i) != '#')
phraseList[c] += phrase.charAt(i);
}
return phraseList;
}
Whenever I use this method with the phrase "Would you rather have tea, eat cookie, or push up?" (omit1 being "," and omit2 being "or") it throws this Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Magpie.separate(Magpie.java:306)
at Magpie.getResponse(Magpie.java:44)
at MagpieRunner.main(MagpieRunner.java:24)
I realize that this has something to do with the counter for the phraseList array, but my attempts to fix it have so far been to no avail.
Any Help?
because if you have even 1 # you will have 2 strings so you need to do c+1 while creating a new array
Like
//creates array list based on number of phrases
String[] phraseList = new String[c+1];
c = 0;
you should use replaceAll(omit1,"#") and not replace(omit1,"#") & replace(omit2,"#")
Can you give more information on where the null is coming ?
Edit:
Have you tried something like ?
phraseList[0]="";
for(int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == '#')
{
c++;
phraseList[c]="";
}else if(phrase.charAt(i) != '#')
{
phraseList[c] += phrase.charAt(i);
}
}
Think of it like commas separating a list:
1 , 2 , 3 , 4 , 5 , 6
If you count the commas, you'll find there are five; but there are six entries in the list. That's because commas separate the entries, but you still have one on each end.
Or think in terms of fence posts and panels: five posts, four panels.
When you create your array to store the phrases, you need one more entry than you had split points, to make sure you have room for all the phrases.
But it would be easier to avoid this entirely and return a List<String> rather than a String[]. That way, you don't need to know the size in advance.
Since other answers showed you what's wrong with your code, here is a cleaner way of separating string that you might like and that behaves more like the actual split() method:
private String[] separate(String phrase, String delim) {
List<String> tokens = new ArrayList<String>();
// add delimiter to the end of the string
// so last token will be included properly
phrase += delim;
// start from index of first deliminator
// i is the index for the deliminator
// j is the index for the first char of the expression before deliminator
int i, j = 0;
// while there are deliminators
while( (i = phrase.indexOf(delim, j)) != -1) {
// obtain the current token from j to deliminator location
String token = phrase.substring(j, i);
// trim leading/trailing spaces of the token and make sure it has any chars
// if it does, add the token to list
if(token.trim().length() != 0) {
tokens.add(token);
}
// update j to the first character after the deliminator
j = i + delim.length();
}
return tokens.toArray(new String[0]);
}
why not use StringTokenizer? (Below is an example from Java doc)
The following is one example of the use of the tokenizer. The code:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
prints the following output:
this
is
a
test
Arrays are indexed starting from 0, but the length of the array is determined with an initial value of 1.
So even though c gives you the number of phrases, its actually the number of indices in the array (since c starts from 0) and not the actual length. The actual length will be c + 1 (since length is calculated starting from 1)
Index 0 | 1 | 2 | 3 | 4
Length 1 | 2 | 3 | 4 | 5
For example, if c = 4 (Index = 4), your String[] will have length 4, when it should be 5. This is what throws that ArrayIndexOutOfBounds. Hope this helps :)

2 dimensional array to string code java

For a program I have to write I am required to turn a 2 dimensional array of single digit intgers into a string of numbers separated by spaces. A test code is provided for me and when I run it, my code fails both arrayToString tests. I am unable to find where my logic error is. Someone help!
public static String arrayToString(int[][] a) {
String aString;
aString = "";
int column;
int row;
for (row = 0; row < a.length; row++) {
for (column = 0; column < a[0].length; column++ ) {
aString = aString + " " + a[row][column];
}
aString = aString + "\n";
}
return aString;
}
I can think of three possible issues.
The test code doesn't want to see the space that you are putting at the beginning of every line.
The test code is passing an array where some of the entries are null. Your code doesn't cope with this.
The test code is passing an array where the entries have different lengths. Your code doesn't cope with this either.
Until you post the test code, we can't see which one the problem is. But you could deal with all three by changing your loop to this.
for (row = 0; row < a.length; row++) {
if (a[row] != null && a[row].length > 0) {
aString = aString + a[row][0];
for (column = 1; column < a[row].length; column++) {
aString = aString + " " + a[row][column];
}
}
aString = aString + "\n";
}
int[][] a = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
public static String arrayToString(int[][] a) {
String aString;
aString = "";
int column;
int row;
for (row = 0; row < a.length; row++) {
for (column = 0; column < a[0].length; column++ ) {
aString = aString + " " + a[row][column];
}
aString = aString + "\n";
}
return aString;
}
Output:
1 2 3
4 5 6
7 8 9
If you skip this line aString = aString + "\n"; your output will look like this
1 2 3 4 5 6 7 8 9
#dawood-ibn-kareem explain good the possible cause of the failure of the test.
With Java 8 Stream, it's pretty easy to do what you want!
With the input: [[1,2,3], [3,4,5], [5,6,7]]
public static String arrayToString(int[][] a) {
return Arrays.stream(a)
.map(s -> Arrays.stream(s)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" "))
)
.collect(Collectors.joining("\n"));
}
Output:
1 2 3
3 4 5
5 6 7
Other method, to separate each line of the 2D array without carriage return
public static String arrayToString(int[][] a) {
return Arrays.stream(a)
.flatMapToInt(Arrays::stream)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" "));
}
Output
1 2 3 3 4 5 5 6 7
Have fun!
Your code is basically OK, except you are putting a leading space at the start of every line. To clean them up before returning, add this line:
aString = aString.replaceAll("(?m)^ ", "");
This uses regex to delete (by replacing with a blank) all spaces at the start of lines. The regex flag (?m) makes ^ match the start of every line of the input (normally ^ matches only the start of input).

Reading a file line and storing variables of different types

I am trying to figure out a way to read from the following text file. I am able to get the first integer in the text file which is numLines. After that point, I am able to get the first integer from the line, but am unable to successfully get each individual group of letters.
for(int i=0; i < numLines; i++){
numVariables = Integer.parseInt(fin.next());
for(int z=0; z < numVariables; z++){
String line = fin.next();
int numRules = Integer.parseInt(line.substring(0, 1));
//Everything up until this point is good
//read and store first capital letter of every line
String variable = line.substring(2,3);
//read and store remaining capital letters that correspond to every line separately
}
}
Text File
3
2 A CC DD
3 A AA z v
2 F f a
I didn't see what is the problem. If you say you have problem of "parsing", you could try:
read a line (String line)
split it into two parts. check here:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String, int)
array =line.split(" ", 2)
then
array[0] is the leading number
array[1] is the rest letters
if you want each part, you could split (" ") without limit.
if you just want to get those Uppercase words, you can do it by regex:
line.split(" ",2); //array[0] is the leading number
apply "(?<= )[A-Z]+(?= )" on array[1], you get all Upper case words.
is that what you want?
String[] words = line.split(("\\s+"); // Any whitespace
int numRules = Integer.parseInt(words[0]);
for (int j = 1; j < words.length; ++j) {
String variable = words[j];
}

Why am I getting java.lang.StringIndexOutOfBoundsException?

I want to write a program that prints words incrementally until a complete sentence appears. For example : I need to write (input), and output:
I
I need
I need to
I need to write.
Here is my code:
public static void main(String[] args) {
String sentence = "I need to write.";
int len = sentence.length();
int numSpace=0;
System.out.println(sentence);
System.out.println(len);
for(int k=0; k<len; k++){
if(sentence.charAt(k)!='\t')
continue;
numSpace++;
}
System.out.println("Found "+numSpace +"\t in the string.");
int n=1;
for (int m = 1; m <=3; m++) {
n=sentence.indexOf('\t',n-1);
System.out.println("ligne"+m+sentence.substring(0, n));
}
}
and this is what I get:
I need to write.
16
Found 0 in the string.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at
java.lang.String.substring(String.java:1937) at
split1.Split1.main(Split1.java:36) Java Result: 1 BUILD SUCCESSFUL
(total time: 0 seconds)
I don't understand why numSpace doesn't count the occurrences of spaces, nor why I don't get the correct output (even if I replace numSpace by 3 for example).
You don't have a \t character, so indexOf(..) returns -1
You try a substring from 0 to -1 - fails
The solution is to check:
if (n > -1) {
System.out.prinltn(...);
}
Your loop looking for numSpace is incorrect. You are looking for a \t which is a tab character, of which there are none in the string.
Further, when you loop in the bottom, you get an exception because you are trying to parse by that same\t, which will again return no results. The value of n in n=sentence.indexOf('\t',n-1); is going to return -1 which means "there is not last index of what you are looking for". Then you try to get an actual substring with the value of -1 which is an invalid substring, so you get an exception.
You are mistaken by the concept of \t which is an escape sequence for a horizontal tab and not for a whitespace character (space). Searching for ' ' would do the trick and find the whitespaces in your sentence.
This looks like homework, so my answer is a hint.
Hint: read the javadoc for String.indexOf paying attention to what it says about the value returned when the string / character is not found.
(In fact - even if this is not formal homework, you are clearly a Java beginner. And beginners need to learn that the javadocs are the first place to look when using an unfamiliar method.)
The easiest way to solve this I guess would be to split the String first by using the function String.split. Something like this:
static void sentence(String snt) {
String[] split = snt.split(" ");
for (int i = 0; i < split.length; i++) {
for (int j = 0; j <= i; j++) {
if (i == 1 && j == 0) System.out.print(split[j]);
else System.out.printf(" %s", split[j]);
}
}
}
As other people pointed out. You are counting every characters except tabs(\t) as a space. You need to check for spaces by
if (sentence.charAt(k) == ' ')
\t represents a tab. To look for a space, just use ' '.
.indexOf() returns -1 if it can't find a character in the string. So we keep looping until .indexOf() returns -1.
Use of continue wasn't really needed here. We increment numSpaces when we encounter a space.
System.out.format is useful when we want to mix literal strings and variables. No ugly +s needed.
String sentence = "I need to write.";
int len = sentence.length();
int numSpace = 0;
for (int k = 0; k < len; k++) {
if (sentence.charAt(k) == ' ') {
numSpace++;
}
}
System.out.format("Found %s in the string.\n", numSpace);
int index = sentence.indexOf(' ');
while(index > -1) {
System.out.println(sentence.substring(0, index));
index = sentence.indexOf(' ', index + 1);
}
System.out.println(sentence);
}
Try this, it should pretty much do what you want. I figure you have already finished this so I just made the code real fast. Read the comments for the reasons behind the code.
public static void main(String[] args) {
String sentence = "I need to write.";
int len = sentence.length();
String[] broken = sentence.split(" "); //Doing this instead of the counting of characters is just easier...
/*
* The split method makes it where it populates the array based on either side of a " "
* (blank space) so at the array index of 0 would be 'I' at 1 would be "need", etc.
*/
boolean done = false;
int n = 0;
while (!done) { // While done is false do the below
for (int i = 0; i <= n; i++) { //This prints out the below however many times the count of 'n' is.
/*
* The reason behind this is so that it will print just 'I' the first time when
* 'n' is 0 (because it only prints once starting at 0, which is 'I') but when 'n' is
* 1 it goes through twice making it print 2 times ('I' then 'need") and so on and so
* forth.
*/
System.out.print(broken[i] + " ");
}
System.out.println(); // Since the above method is a print this puts an '\n' (enter) moving the next prints on the next line
n++; //Makes 'n' go up so that it is larger for the next go around
if (n == broken.length) { //the '.length' portion says how many indexes there are in the array broken
/* If you don't have this then the 'while' will go on forever. basically when 'n' hits
* the same number as the amount of words in the array it stops printing.
*/
done = true;
}
}
}

Categories

Resources