I have a 2D String array freq:
String freq[][] = new String[26][2];
and I would like to use the contents of the first column only with new String(freq) which would work if freq is a normal array. However I would like to do this with the first column of my 2D array, or would I have to use two 1D arrays to do this:
String freq[][] = new String[26][2];
int free = 0;
for (int b = 0; b < words.length; b++) {
for (int l = 0; l < words[b][0].length(); l++) {
if (new String(freq[0]).indexOf(words[b][0].charAt(l)) < 0) {
freq[free][0] = Character.toString(words[b][0].charAt(l));
free++;
}
}
}
Thanks! :)
Use a StringBuilder and concat all the values (replace 8 with whatever your average word length is):
final StringBuilder builder = new StringBuilder(words.length * 8);
for (String[] nestedWords : words)
{
builder.append(nestedWords[0]);
}
return builder.toString();
You could also do this in java 8 as so:
return Arrays.stream(words).map(a -> a[0]).collect(Collectors.joining());
I'm not quiet sure if I understand what you want to achive but if you only want to iterate over the first column just do something like this and just drop the inner loop
for(int i = 0; i < words.length; i++) {
//Do stuff with words[i][0], e.g.
words[i][0] = Some_usefull_thing;
}
Related
ArrayList<String> gradeN = new ArrayList<String>();
gradeN.add("one");
gradeN.add("two");
int num2 = 0;
while (num<5){
gradeN.get(0).concat("*");
num2++;
}
System.out.println(gradeN.get(0));
This is not working.
I want output like this:
one*****
and do this in a loop..
There are 2 mistakes in your code:
The variable incremented in your while loop is different to the one used in the condition.
Strings are immutable. String.concat returns a different String object and does not modify the original String. That means the value in your List is not modified. To fix this, use List.set to replace the old value in the list with a new one.
int num2 = 0;
while (num2 < 5) {
String newValue = gradeN.get(0).concat("*");
gradeN.set(0, newValue);
num2++;
}
Your question is somewhat unclear. Do you always want to add 5 stars to the string? If so, a constant string with 5 stars in it makes more sense than a loop. And I assume you really meant to do this for every element of gradeN? So something like this:
ArrayList<String> gradeN = new ArrayList<String>();
gradeN.add("one");
gradeN.add("two");
for (int i = 0; i < gradeN.size(); i++) {
gradeN.set(i, gradeN.get(i) + "*****");
System.out.println(gradeN.get(i));
}
If the number of stars added may vary and you really wanted to append them in a loop, then you could use StringBuilder to build it up:
ArrayList<String> gradeN = new ArrayList<String>();
gradeN.add("one");
gradeN.add("two");
int num = 5;
for (int i = 0; i < gradeN.size(); i++) {
StringBuilder stars = new StringBuilder(gradeN.get(i));
for (int j = 0; j < num; j++) {
stars.append('*');
}
gradeN.set(i, stars.toString());
System.out.println(gradeN.get(i));
}
One solution is to get the value of gradeN.get(0) on every loop and append * to it.
i.e.:
int num2 = 0;
while (num2<5){
gradeN.set(0, gradeN.get(0)+"*");
num2++;}
Output:
one*****
Demo:
http://ideone.com/XQvWqX
I'm taking care of some other methods and I don't know what to do with this one. I want to change the order of the string inside the array (not the order of the string*s*), but this isn't accepted. Any ideas?
public void invert() {
for(int i = 0; i < array.length; i++){
for(int j = 0, k = array[i].length() - 1; j < k; j++, k--){
char a = array[i].charAt(j);
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(k) = a; //AND HERE
}
}
}
EDIT: I'll leave here what I mean.
I have an array = {"Hello", "Goodbye"}
I want to change it to {"olleH", "eybdooG"}
Java string are immutable. You can't change them.
(But you can convert the string to a StringBuilder - http://docs.oracle.com/javase/tutorial/java/data/buffers.html - which is essentialy a mutable string, change the characters, and then convert the StrignBuilder back to String.)
Try this code (I haven't tested it, but I hope it works):
for(int i = 0; i < array.length; i++) {
StringBuilder b = new StringBuilder(array[i]);
for(int j = 0, k = b.length() - 1; j < k; j++, k--){
char a = b.charAt(j);
b.setCharAt(j, array[k].charAt(k));
b.setCharAt(k, a);
}
array[i] = b.toString();
}
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(a) returns a value not a variable. You are trying to assign a value to a value which doesn't make any sense.
java String is immutable. You can't change it.
Use StringBuilder which has setCharAt(int index,
char ch); function which is what you are probably wanting.
The most simple way is, to reverse letter with StringBuilder.reverse() method. Try,
for(String str : array){
System.out.println(new StringBuilder(str).reverse());
}
Just use this on every String in your array:
String reversed = new StringBuilder(stringFromArray).reverse().toString();
try doing new StringBuilder(array[i]).reverse().toString();
you would have to create a substring.
array[i]= array[i].substring(0,j) + array[k].charAt(k) + array[i].substring(j+1);
This would do the required edit i beleive
I've been working on a Java lab that wants us to have the user enter two digits up to 50 digits long and add them together. I've successfully been able to complete everything except for when the two arrays have a different length. I've been toying around with the code for a while, but I keep coming up short. Can anyone look at the code for this and have any suggestions? Thanks!
int[] number1 = new int[input1.length()];
int[] number2 = new int[input2.length()];
int[] answer = new int[input1.length()];
if(number1.length > number2.length){
number2 = new int[number1.length];
for(int i = 0; i < number2.length - number1.length; i++){
number2[i] = 0;
}
}
if(number2.length > number1.length){
number1 = new int[number2.length];
for(int i = 0; i < number1.length - number2.length; i++){
number1[i] = 0;
}
}
Whenever I add, say 120 and 12, it says there's an Array out of bounds error.
First thing you need to do is get the numbers into an int array. Do that by Splitting string to char array. Then convert to int array. Then add.
String input1 = scanner.nextLine().trim(); <-- get input as String
String input2 = scanner.nextLine().trim();
char[] array1 = input1.toCharArray(); <-- split to char array
char[] array2 = input2.toCharArray();
// convert to int array
int[] intArray1 = new int[array1.length]; <-- declare int array
int[] intArray2 = new int[array2.length];
for (int i = 0; i < array1.length; i++){
intArray1[i] = Integer.parseInt(String.valueOf(array1[i])); <-- convert to int
}
for (int i = 0; i < array2.legnth; i++){
intArray2[i] = Integer.parseInt(String.valueOf(array2[i]));
}
// check which one is larger and add to that one
if (intArray1.length > intArray2.length){
for (int i = 0; i < intArray2.length; i++){
intArray1[i] += intArray2[i]; <-- add values
}
System.out.println(Arrays.toString(intArray1); <-- print largest
} else {
for (int i = 0; i < intArray1.length; i++){
intArray2[i] += intArray1[i];
}
System.out.println(Arrays.toString(intArray2);
}
If you want to get the number representation printed instead of an array, instead of the System.out.println(), use this
StringBuilder sb = new StringBuilder();
for (int i : intArray1){
sb.append(String.valueOf(i));
}
System.out.println(sb.toString());
So 123 and 12 will print out 233
My understanding of your code is, you try to pre-append (push from head) 0s to the shorter array. Look at the first if-block. The length of number1 is larger than what of number2. Thus, number2.length - number1.length is negtive. Then, in the for loop, i < number2.length - number1.length is always ture. (I am not familiar with java. I guess array's length is an integer.) And you still have to copy the rest of array.
The correct code should be,
if(number1.length > number2.length) {
int[] number3 = new int[number1.length];
for(int i = 0; i < number1.length - number2.length; ++i) {
number3[i] = 0;
}
for(int i = 0; i < number2.length; ++i) {
number3[i + number1.length - number2.length] = number2[i];
}
number2 = number3;
}
BTW, the second if-block should be changed in a similar way. Perhaps, java provides an API link insert(0, 0) for array object. It will be easier to implement.
Below is my code:
public int maxTurns = 0;
public String[][] bombBoard = new String[9][9];
...
public void loadBombs()
{
//loadArray();
Random randomGen = new Random();
for (int u=1; u<=9; u++)
{
int randomRow = randomGen.nextInt(9);
int randomCol= randomGen.nextInt(9);
bombBoard[randomRow][randomCol] = "#";
}
//counting #'s -- setting variable
for (int d = 0; d < bombBoard[bombRow].length; d++)
{
for (int e = 0; e < bombBoard[bombCol].length; e++)
{
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
{
maxTurns++;
}
}
}
All I want to do is count the amount of (#)'s in the multidimensional array and assign it to a variable called maxTurns.
Probably very simple, just having a super hard time with it tonight. Too much time away from Java >.<
This line is equating the character # with the entire dth row or eth row. Does not make sense really because an array row cannot equal to a single character.
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
Instead, access a single cell like this
if (bombBoard[d][e].equals("#"))
And initialize maxTurns before counting i.e. before your for loop:
maxTurns = 0;
You need to change the if codition
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
to
if (bombBoard[d][e].equals("#"))
You are using 2D Array, and do array[i][j] can populate its value for a gavin position.
do you want to count from the whole array or certain parts of the array only?
From the code snippet you gave above, I can't really tell how you iterate the array since I'm not sure what is
bombBoard[bombRow].length and bombBoard[bombCol].length
But if you want to iterate the whole array, think you should just use:
for (int d = 0; d < 9; d++) // as you declared earlier, the size of array is 9
{
for (int e = 0; e < 9; e++) // as you declared earlier, the size of array is 9
{
if (bombBoard[d][e].equals("#"))
{
maxTurns++;
}
}
}
I'm having trouble with this, maybe you could help me:
I have 3 strings like: word1, word2, word3 and I have to build a matrix with them, like this:
on the first row : word1("ABC"), second row: word2("DEF") and third row: word3("GHI").
A|B|C
D|E|F
G|H|I
I need this because after that I have to check if the formed words ("ADG","BEH","CFI") are in an array of words. And I don't know how to put those strings in the matrix so I can check. Any help is useful.
Thanks
Based on this comment:
the words have the same size, because the matrix is actually like a puzzle. I choose randomly 3 words from an array, put them in a matrix and check after that if the words resulted are from the same array.
I'll assume some things in order to make this work (since we don't have enough info):
You have an array of Strings where you have all the words
private String[] words;
You have a method to randomly pick up 3 Strings from this array.
private String s1, s2, s3;
public void pickThreeRandomWords() {
s1 = aRandomWord(words);
s2 = aRandomWord(words);
s3 = aRandomWord(words);
//or maybe another fancy algorithm to get this...
}
So you would need an array of array of chars based on these 3 Strings. This code could do the work for you:
public char[][] createMatrixFromStrings(String s1, String s2, String s3) {
char[][] theMatrix = new char[3][]; //yes, hardcoded
theMatrix[0] = s1.toCharArray();
theMatrix[1] = s2.toCharArray();
theMatrix[2] = s3.toCharArray();
return theMatrix;
}
Of course, if you would want to make this method to support more than 3 Strings you can make the method to receive a random quantity of Strings:
public char[][] createMatrixFromStrings(String ... strings) {
if (strings == null || strings.length == 0) return null;
char[][] theMatrix = new char[strings.length][];
int i = 0;
for(String s : strings) {
theMatrix[i++] = s.toCharArray();
}
return theMatrix;
}
You can build the result words without a matrix:
List<String> verticalWords = new ArrayList<String>();
for (int i = 0; i < horizontalLen; i++){
String currentWord = "";
for (int j = 0; j < wordCount; j++)
currentWord += words.get(j).get(i);
verticalWords.add(currentWord);
}
P.S. For the currentWord you can use a StringBuilder to make it more efficient, but I doubt it is highly needed here.
Java doesn't have matrix.It has array of array
So,you can try this
List<char[]> lst=new ArrayList();//stores a list of char[]
lst.add(("ADC".toCharArray()));//adds array of characters i.e 'A','D','C'
lst.add(("DEF".toCharArray()));
lst.get(0)[0];//A
lst.get(1)[0];//D
Now you can iterate vertically
for(int i=0;i<lst.size();i++)temp+=lst.get(i)[0];
temp would have AD which you can now cross check with equals method
The main thrust of this goal is that you're taking a one-dimensional value, and converting it into a two-dimensional value. There are many ways you can do this, but here are the two that come off the top of my head:
Set up a nested while loop to iterate over the first dimension, and when it reaches the length, reset and cause the outer loop to increment, much like a clock
You can create a new subarray using ArrayUtils.toSubArray(), and with some finagling, get that to work:
Create a new row of the array each time, based on the dimension slices you want to hit up. I'll leave figuring this one out as an exercise for the reader. But here's a hint:
for(int i = 0; i < theDimension; i++, j += 3) {
ret[i] = ArrayUtils.subarray(word, i*theDimension, j);
}
Lastly, I assume that there's a restraint on the type of input you can receive. The matrix must be square, so I enforce that restriction before we build the array.
I strongly encourage you to poke and prod this answer, and not just blindly copy it into your schoolwork. Understand what it's doing so you can reproduce it when you're asked to again in the future.
public char[][] toMatrix(int theDimension, String theEntireWord) {
if(theEntireWord.length() != theDimension * theDimension) {
throw new IllegalArgumentException("impossible to add string to matrix of uneven dimension");
}
char[][] ret = new char[theDimension][theDimension];
int i = 0;
int j = 0;
while(i < theDimension) {
if(j == theDimension) {
j = 0;
++i;
} else {
ret[i][j] = theEntireWord.charAt((i * theDimension) + j);
j++;
}
}
return ret;
}
I think this will sort your problem.
package printing;
public class Matrix {
public static void main(String[] args) {
//Length can define as you wish
String[] max = new String[10];
String[] out = null;
//Your Inputs
max[0]="ADG";
max[1]="BEH";
max[2]="CFI";
//following for loop iterate your inputs
for (int i = 0; i < max.length; i++) {
if(out==null){out= new String[max.length];}
String string = max[i];
if(string==null){ break;}
//Here breaking input(words) one by one into letters for later contcatnating.
String[] row = string.split("");
for (int j = 0; j < row.length; j++) {
String string1 = row[j];
// System.out.println(string1);
//create the values for rows
if(out[j]!=null){ out[j]=out[j]+string1;}
else{
out[j]=string1;
}
}
}
//following for loop will out put your matrix.
for (int i = 0; i < out.length; i++) {
String string = out[i];
if(out[i]==null){break;}
System.out.println(out[i]);
}
}
}