How Do I make matrix 16 x 16 from String? - java

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++;
}
}

Related

There is string "naveen" , want output as "eennav"

I have string in java "naveen" i want output as "eennav". Please help me out in this. The idea is that the characters are to be ordered in order of frequency, and, where frequencies are the same, alphabetically.
Thanks
I have tried to find duplicates in the string , but am not able to get the required output .
String str="naveen";
int count =0;
char[] charr=str.toCharArray();
for(int i=0;i<charr.length;i++) {
//System.out.println(s[i]);
for(int j=i+1;j<charr.length;j++) {
if(charr[i]==(charr[j])) {
System.out.println(charr[i]);
}
Assuming the question is asking us to take a string containing only lower case letters and organize them by frequency of letters (high to low) and within that by alphabetical order, we can do it as below.
The strategy is first to make a pass through the characters of the input string and count the number of occurrences of each. Then we look through the counts for letters and find the largest. Working from the largest down to 1, we run through the alphabet for characters that occur that many times, and append that many of them to the result string.
There is a little bit of work involved here to convert back and forth from 'a' to 0 and 0 to 'a' and so on to 25 and 'z'.
This approach could be extended, but since the question didn't specify, I chose to make simplifying assumptions. I also did not work on optimizing, just getting it to work.
public class MyClass {
public static void main(String args[]) {
String str = "naveen"; //this string may change, but it is assumed to be all lower case letters by this implementation
int[] counts = new int[26]; //frequency count of letters a to z
for (int i = 0; i < 26; i++) {
counts[i] = 0; // intially 0 of any letter
}
char[] charr = str.toCharArray();
for (int i = 0; i < charr.length; i++) {
counts[(int)(charr[i]) - (int)('a')]++; // increment corresponding spot in counts array, spot 0 for 'a' through 25 for 'z'
}
int maxCount = counts[0]; // now find the most occurrences of any letter
for (int i = 1; i < counts.length; i++) {
if (counts[i] > maxCount) {
maxCount = counts[i];
}
}
String result = ""; // string to return
for (int j = maxCount; j > 0; j--) { // work down from most frequently occuring, within that alphabetically
for (int i = 0; i < 26; i++) {
if (counts[i] == j) {
//System.out.println("there are "+j+" of the letter "+(char)((int)('a'+i)));
for (int k = 0; k < j; k++) {
result = result + (char)((int)('a' + i));
}
};
}
}
System.out.println(result);
}
}

How to loop this statement with 3 changing values to setText for 40 textfields?

Here is the code when I haven't stored in a list. This gets what I want to display in different textfields but I want it to be shorter so I want to loop it.
//"answerStoration.retrieveDataChoices(i,TB)" is a function from other class that returns an arraylist;
quizAnswer1store.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswer2store.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswer3store.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswer4store.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswer1store2.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswer2store2.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswer3store2.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswer4store2.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswer1store3.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswer2store3.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswer3store3.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswer4store3.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
I stored it in a List "quizAnswerSTORE" and I tried to loop but doesnt work.
int k = 0;
for(int i = 0; i<quizAnswerSTORE.size(); i++){
for(int j = 1; j < 11; j++){
while(k<4){
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
The expected result is to diplay different values from a database in different 40 txtfields. Because each time the loop values increments, it rolls through my database with different values. J variable represents the id in my database. And the K is an index in the values taken in the arrayList returned by retrieveDataAnswers function from a four columned database.
There you go. I hope you can solve this.
You can use mod to control maximun int values, for example i % 10 can't take values more than 10.
Example:
public class Main {
public static void main(String[] args) {
int j = 1;
int k = 0;
for(int i = 0; i < 40; i++) {
System.out.println("quizAnswerSTORE"+i+".setText(answerStoration.retrieveDataChoices("+j+",TB).get("+k+"));");
k = (k + 1)%4;
if( k == 0) {
j = (j+1) % 11;
}
}
}
}
output:
quizAnswerSTORE0.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswerSTORE1.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswerSTORE2.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswerSTORE3.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswerSTORE4.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswerSTORE5.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswerSTORE6.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswerSTORE7.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswerSTORE8.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswerSTORE9.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswerSTORE10.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswerSTORE11.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
...
quizAnswerSTORE38.setText(answerStoration.retrieveDataChoices(10,TB).get(2));
quizAnswerSTORE39.setText(answerStoration.retrieveDataChoices(10,TB).get(3));
Try to be consistent with your indentation and line up closing brackets '}' with their corresponding statement.
The first problem I see with this code is that k is never incremented inside the while loop so it will always have the same value and loop forever. The second problem I see is that k is not reset after the while loop so when it goes through the loop the first time (and is correctly incremented) it will stay at a value of 4 and the loop will be skipped every time after that.
I'm not sure what you're trying to achieve (I could use some more information or a sample output) but to begin with you can correct the loop error by changing the while loop to a for loop like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
for (int k = 0; k < 4; k++) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
Alternatively, if you wanted to keep the while loop, you could so it like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
int k = 0; // Set k inside the 2nd loop and it will reset to 0 after the while loop
while(k < 4) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
k++; // Shorthand for k += 1 which is shorthand for k = k + 1
}
}
}

Fill a 2D array with random uppercase characters

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 '<')

How to create multiple arrays with a loop?

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;
}

I'm trying to reverse an array line by line

To clarify, this IS a homework assignment. I'm merely looking for advice, I'm not looking for someone to do my homework for me.
I've already done the first half. It uses two arrays to print an Asterisk design (in this case, the letter 'S'. That works fine. Then, I skip two lines and print the design but flipped (so each line is reversed). It seems to be working fine, but when I run the program, it prints two S's and the second one isn't reversed. Any ideas of what I'm doing wrong?
public class Design {
public static void main (String [] args) {
char [] array = new char [150];
for (int index = 0; index < array.length; index ++)
{
array [index] = '#';
}
int [] indexNumbers = {
0,1,2,3,4,5,6,7,8,9,10,20,30,40,50,
60,70,71,72,73,74,75,76,77,78,79,89,99,109,119,129,139,140,
141,142,143,144,145,146,147,148,149
};
for (int i = 0; i < indexNumbers.length; i++)
{
array [indexNumbers[i]] = ' ';
}
for (int index = 0; index < array.length; index ++)
{
if (index % 10 == 0 && index > 0)
System.out.println();
System.out.print (array[index]);
}
//Now, to reverse the letter
System.out.println();
System.out.println();
int lines = 5;
for (int i = 0; i< array.length; i++){
if (i >= lines)
lines += 10;
char temp = array [i];
array [i] = array [lines - i - 1];
array [lines - i - 1] = temp;
}
for (int index = 0; index < array.length; index ++)
{
if (index % 10 == 0 && index > 0)
System.out.println();
System.out.print (array[index]);
}
}
}
EDIT: Yeah... the design is in spaces, everything else is asterisks.
your reversing is a bit confused.... makes it easier if you do it in two loops.
for (int row = 0; row < (array.Length / 10); row++)
{
for (int col = 0; col < 5; col++)
{
int rowStart = row * 10;
int rowEnd = rowStart + 9;
char temp = array[rowStart + col];
array[rowStart + col] = array[rowEnd - col];
array[rowEnd - col] = temp;
}
}
First, why don't you use String[] or char[][]? Instead you are using a simple array to put multiple lines within. This makes your code confuse and brittle.
To swap an array, the rule is generally simple: Get the first and the last line and swap them. Get the second and the second last, and swap them, get the third and the third last and swap them... Until you get to the middle. This will be much easier if you have an array where each element is a line (like in an String[] or in an char[][]).
If you need to keep the idea of a simple char[] where each 10-char block is a line, simply swap each 10-char block like I stated above.
If you don't want to change the general behaviour of your program, this is the problematic block:
int lines = 5;
for (int i = 0; i< array.length; i++){
if (i >= lines)
lines += 10;
char temp = array [i];
array [i] = array [lines - i - 1];
array [lines - i - 1] = temp;
}
You are not swapping lines here, instead you are swapping chars. This way, your if is not checking and skipping lines, but is instead checking and skipping chars.
This is better:
int lines = array.length / 10;
for (int i = 0; i<= lines / 2; i++){
for (int j = 0; j < 10; j++) {
char t = array[i * 10 + j];
array[i * 10 + j] = array[(lines - i - 1) * 10 + j];
array[(lines - i - 1) * 10 + j] = t;
}
}
So..
First of all, start by printing '#' instead of ' ', and '.' instead of '#'. You will see more clearly what's going on.
Second, you have a problem in the reverse, you are actually not reversing anything, the way you calculate the index lines - i - 1 is wrong. The good way is (i / 10) * 10 + (10 - (i % 10)) -1. Yep, is kinda horrible, but if you want that in one line, using a one-dimension array, there it is. Now it's up to you to understand it, and integrate it in your code ;)

Categories

Resources