I have this constructor for building a word search game (or are those called "alphabet soups"?). Its purpose is to create a two-dimensional array and then fill it with random uppercase letters.
SopaLetras(int numFilas, int numColumnas){
this.numFilas = numFilas;
this.numColumnas = numColumnas;
char letra;
cuadricula = new char[numFilas][numColumnas];
for (int i = 0; i > numFilas; i++){
for (int j = 0; j < numColumnas; j++){
letra = (char)(65+(int)(Math.random()*26));
cuadricula[i][j] = letra;
}
}
}
However, whenever i initialize this cuadricula[][] and try to check for any of its spaces, it always returns an empty character. I've checked the usage of Math.random(), it is correct and that statement is able to return a random uppercase character when putting it in a System.out.println().
¿What is it that makes me unable to assign that char to that place in the array?
Any help would be appreciated.
You never enter the first loop.
Instead of for (int i = 0; i > numFilas; i++) you should write for (int i = 0; i < numFilas; i++) (compare '<')
Related
The first 4 values are set properly in the new array. It has to do with something with my variable 'count' which is not being set properly. The goal of the program is to simply grab the even numbers, and put them in a new array.
I have added 4 to count as a test, and that seems to work perfectly but I dont think that is the issue here.
int[] list = {8,5,4,11,12,2,1,3,10,6,7};
int count = 0;
int gr = 0;
for(int n=0; n<list.length; n++)
{
if(list[n] % 2 == 0)
{
count++;
}
}
int[] evn = new int[count];
for(int k = 0; k<=count; k++)
{
if(list[k] % 2 == 0)
evn[gr++] = list[k];
}
return evn;
Currently, the array prints "8,4,12,2,0,0" when it should print "8,4,12,2,10,6"
This happens because count is always less than the size of the array(list.length), so in the second for-loop you are never iterating till the end of the array.
Change your second for-loop to iterate till the end of the array as shown below :
for(int k = 0; k < list.length; k++)
You're only traversing part of list, as stated in the for condition:
for(int k = 0; k<=count; k++)
^--here--^
This is because count has a lower value than the length of the original array. Change this condition to traverse the whole array:
for(int k = 0; k<list.length; k++)
To traverse the whole list change the following:
for(int k = 0; k<=count; k++)
To
for(int k = 0; k<list.length; k++)
This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 5 years ago.
My code needs to get user input, and print the letter that occurred the most in that input. I know I need to do something along the lines of switching the String input into char[], but what to do after words? how to check for each character's apperance?
any ideas how?
I need to do it using only loops & Wrapper classes, it's a part of an assignment so I have to be specific.
public static void main(String[] args){
int frequencyCount = 0; //count each letters frequency
char popularChar = ' '; //letter with the most frequency
for (int i = 0; i < array.length; i++){
for(int c = 0; c < array.length; c++){
frequencyCount++;
}
}
To get the most frequent character you need to know the frequency of every distinct character in first place.
int frequencyCount = 0, count;
char popularChar, tempChar;
for (int i = 0; i < array.length; i++){
temp = array[i];
for(int c = 0; c < array.length; c++){
count = 0;
if(tempChar == array[c]){
count++;}
}
if(count > frequencyCount){
frequencyCount = count;
popularChar = tempChar;}
}
Hope this will help. And yes, you need to optimize it a lot. Happy coding :)
I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}
So let's say I have an array called arr with the values &&&&.&&. I want to find the number of ampersands (&) that are after the decimal point and store the value into numDecimalDigits.
int numDecimalDigits = 0;
char[] arr = new char[7]
for (int i = 0; i < str.length(); i ++)
{
for (int decimal = (arr[pos] = '.'); decimal <= arr.length; decimal ++)
{
numDecimalDigits += 1;
}
}
I'm not sure if this is the right approach. So the outside for loop runs through each index value of the array. The inner for loop starts at the decimal, and ends at the end of the array. Every time a new value is found, numDecimalDigits is added by one. However, in my code I think numDecimalDigits is returning an incorrect value.
You only need one loop:
boolean foundDot = false;
for (int i = 0; i < arr.length; i++) {
if(arr[i] == '.') {
foundDot = true;
} else if(foundDot) {
numDecimalDigits ++;
}
}
No need to use array. It would be easy like this:(Assuming str value must contains one '.' )
int numDecimalDigits = str.split("\\.")[1].length();
Or you can do by subtracting str.length()-1 with indexOf(".")
int numDecimalDigits = str.length()-1 - str.indexOf(".");
I have a string
String word = "FrenciusLeonardusNaibaho";
while I'm trying to make matrix like this:
char matriks[][] = new char[16][16];
int k = 0;
for (int i = 1; i < 16; i++) {
for (int j = 1; j < 16; j++) {
matriks[i][j] = word.charAt(k);
k++;
}
}
I got this error
String index out of range: 24
How can I achieve this?
Thanks..
You are overflowing beyond the end of word at word.charAt(k);. Basically you dont have enough alphabets to fill your matrix.
You can do something like this
if(k >= word.length())
break;
Below the inner loop. Or you can init the element to some default value with this condition.
Additionally as others have mentioned, i,j should start at 0, unless you have a good reason to start at 1.
char matriks[][] = new char[16][16];
int k = 0;
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
matriks[i][j] = word.charAt(k%word.length());
k++;
}
}
So it can go from start to end,then restart.
try adding
if(k >= word.length())
k = 0;
to your inner for loop, this will continue filling the array from the beginning of the word.
'Out of bounds' or 'out of range' occures when you try to read or write in an array, list, string or whatever with a range beyond it's boundary. You can't read a a character at index 8 when your string contains only 7 character. It's not your string's RAM and it would cause RAM corruption like it is happening sometimes in C-arrays.
When you set up your array and your for-loop try to check if you are still in bounds of your string with a size or length function of your container. In special case of string it is length.
I think you are trying to split a list of names stored in a string. In such a case it is easier to create a dynamic container, something like list (http://www.easywayserver.com/blog/java-list-example/).
Here I have a little example. For those purposes I prefer a while-loop. In cases I know the length of a list at least at runtime without interpreting data a for-loop is a good choice, but not in this:
String names = "Foo Bar";
List<String> seperatedNames = new List<String>();
String name = "";
int i = 0;
while (i < names.length()) {
if (names.charAt(i) == ' ') { // you can check for upper case char too
seperatedNames.add(name); // add name to list
name = ""; // clear name-buffer
i++; // increment i, else it would produce an infinite loop
}
name += names.charAt(i++); // add current char to name-buffer and increment current char
}
I hope I could help a bit.
of course, you will get this error surely because the character in your word are only 24 character.
to avoid this your need to check the length of your word and need to break the all looping.
Try this code.
char matriks[][] = new char[16][16];
int k = 0;
int lenght = word.length();
outerloop:
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
matriks[i][j] = word.charAt(k);
k++;
if(k >= lenght){
break outerloop;
}
}
}
You are filling 16x16 array and iterating the loop 16x16 times but your word size is less than 16x16. So put a check when k becomes equal to the word length then terminate the loop.Change your code like this.
char matriks[][] = new char[16][16];
int k = 0;
for (int i = 1; i < 16; i++) {
for (int j = 1; j < 16; j++) {
if(k >=word.length)
break;
matriks[i][j] = word.charAt(k);
k++;
}
}