I am attempting to generate a gameboard as a 2D array of chars, the top layer of the array is displaying the char versions of ints(no problems there), however the code is throwing an error message, as displayed below.
java -classpath .:/run_dir/junit-4.12.jar:target/dependency/*
Main Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
at Main.genVisual(Main.java:16)
at Main.main(Main.java:3)
Here is my code:
class Main {
public static void main(String[] args) {
char[][] hehe = genVisual(7, 2);
}
public static char[][] genVisual(int length, int height) {
char[][] visual = new char[height][length];
char character = ' ';
for (int n = 0; n < height; n++) {
for (int i = 0; n < length; n++) {
if (n == 0) {
int w = i + 1;
character = (char) w;
visual[n][i] = character;
} else {
visual[n][i] = 'x';
}
}
}
return visual;
}
}
I have tried changing the values that control the list size in the for loop and have browsed this website for answers, however I do not see any issues with the program.
Related
How to use multiple methods in a code? First it asks for the size of an array, then for the numbers of the element. One method is rounding numbers with a special rule.
Second method is a void method which modifies the array. Third method is making a new array with the modified values and returns to this array.
package tombtombbekerekit;
import java.util.Scanner;
public class TombTombbeKerekit {
public static int round(int osszeg)
{
int last_Digit = osszeg % 10;
if(last_Digit < 3)
return osszeg - last_Digit;
else if(last_Digit > 7)
return osszeg + (10 - last_Digit);
else
return osszeg - (last_Digit) + 5;
}
public static void roundSelf(int [] numbers)
{
int[] array = numbers;
for (int i = 0; i < array.length; i++)
return;
}
public static int [] roundNew(int [] numbers)
{
int [] newArray = new int[numbers.length];
return newArray;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Kérem az összegek számát: ");
int size = sc.nextInt();
System.out.println("Kérem az összegeket: ");
int [] array = new int[size];
for (int i = 0; i < array.length; i ++)
{
array[i] = sc.nextInt();
}
int [] kerek = roundNew(array);
System.out.println("Kerekítve: ");
for (int i = 0; i < kerek.length; i++)
System.out.println(kerek[i]);
}
}
You should write your own function. Just find the rule for the rounding. You can use n%10 to get the last digit of an integer named n.
I've written something but haven't tested it, I believe it should work. Check it out:
public int weirdRounding(int n)
{
int last_Digit = n % 10;
if(last_Digit < 3)
return n - last_Digit;
else if(last_Digit > 7)
return n + (10 - last_Digit);
else // the last digit is 3,4,5,6,7
return n - (last_Digit) + 5;
}
Note: You should probably make this code more readable if you're going to use it. For example define int LOWER_BOUND = 3 and int UPPER_BOUND = 7 instead of using '3' and '7', you could also wrap the ugly expressions with functions (e.g. roundUp, roundToFive ..). #Magic_Numbers_Are_Bad
Im creating a program that will generate a word search game but am still in the early stages. I have taken all the input from a text file and converted it into an array that provides the word, its initial row and column starting point, and whether its horizontal or vertical. I have started a new method that will create the basic puzzle array that contains only the word to be hidden. My problem is that im consistently getting:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at WordSearch.createPuzzle(WordSearch.java:50)
at WordSearch.main(WordSearch.java:25)
The snippet of code that is the issue is as follows:
public static char[][] createPuzzle(int rows, int cols, Word[] words) {
char[][] puzzle = new char[rows][cols];
for (int i = 0; i <= 9; i++) {
int xcord = words[i].getRow();
int ycord = words[i].getCol();
if (words[i].isHorizontal() == true) {
String word = words[i].getWord();
for (int j = 0; j < word.length(); j++ ) {
puzzle[xcord + j][ycord] = word.charAt(j);
}
} else {
String word = words[i].getWord();
for (int k = 0; k < word.length(); k++) {
puzzle[xcord][ycord + k] = word.charAt(k);
}
}
}
return puzzle;
}
public static void displayPuzzle(String title, char[][] puzzle) {
System.out.println("" + title);
for(int i = 0; i < puzzle.length; i++) {
for(int j = 0; j < puzzle[i].length; j++) {
System.out.print(puzzle[i][j] + " ");
}
System.out.println();
}
}
with:
displayPuzzle(title, createPuzzle(11, 26, words));
in my main method alongside the code that creates the words array.
puzzle[xcord + j][ycord] = word.charAt(j);
If xcord is 8 and j is > 1 you will get an index out of bounds error because your puzzle board only has 9 rows.
You need to make sure your words don't go past the puzzle boundaries.
Error : java.lang.IndexOutOfBoundsException: Invalid index 70, size is 10;
I have created a function to create random Integer ArrayList, and to do some operations with it, now i a m trying to adapt it to Chars,and i got strange error, as it seems to me,the default chars array size is bigger then Integer one, but i am not sure.What can i do with this code?
Function fails here : numbers.set(rightNumbers.get(k),answer.charAt(k));
#Override
public void charactersRandomise(String answer) {
final String alphabet = "ABSDEFGHMN";
final int N = alphabet.length();
ArrayList<Character> numbers = new ArrayList<Character>();
ArrayList<Character> rightNumbers = new ArrayList<Character>();
Random randomGenerator = new Random();
int i=0;
Log.d("size",String.valueOf(N));
while (numbers.size() < 10) {
char random = alphabet.charAt(randomGenerator.nextInt(N));
if (!numbers.contains(random)) {
numbers.add(random);
Log.d("numbers", numbers.get(i).toString());
i++;
}
}
int j=0;
while (rightNumbers.size() < answer.length()) {
char random = alphabet.charAt(randomGenerator.nextInt(N));
if (!rightNumbers.contains(random)) {
rightNumbers.add(random);
Log.d("RightNumbers",rightNumbers.get(j).toString());
j++;
}
}
for(int k =0;k<rightNumbers.size();k++){
numbers.set(rightNumbers.get(k),answer.charAt(k));
Log.d(rightNumbers.get(k)+"", numbers.get(rightNumbers.get(k)).toString());
}
for (int h=0;h<numbers.size()-1;h++) {
Log.d("newNumber", String.valueOf(numbers.get(h)));
}
for(int m=0;m<buttons.length;m++){
buttons[m].setText(numbers.get(m) + "");
}
}
numbers.set(rightNumbers.get(k),answer.charAt(k)); - this expression rightNumbers.get(k) retrieves a character. In ASCII this character ( as i can see it is F) is converted to the number 70 in int and that is why the exception occurs.
Replace this with this:
numbers.set(k ,answer.charAt(k));
So I need to make a diamond_look of numbers using 2D array in Java. I got my results but with null before the diamond. For drawNumDiamond(9) I have to get a diamond look that goes until 5 and back. I know I can make it without using array, but I want to learn more about 2D arrays :this is how it should look like and what are my results
public class Example1{
private static void drawNumDiamond(int h) {
if(h%2 != 0) {
int size = h/2 +1;
int count = 1;
int loop = 1;
String[][] dijamant = new String[h][];
for(int row = 0; row < dijamant.length; row++) {
dijamant[row] = new String[row+1];
for(int kolona=0; kolona<=row; kolona++) {
dijamant[0][0] = "1";
for(int i=0; i< loop;i++) {
dijamant[row][kolona]+= count;
}
}
count++;
loop+=2;
}
for (int k = 0; k < size; k++) {
System.out.printf("%" + h + "s", dijamant[k]);
h++;
System.out.println();
}
h--;
for (int q = size - 2; q>=0; q--) {
h--;
System.out.printf("%" + h + "s", dijamant[q]);
System.out.println();
}
}
}
public static void main(String[] args) {
drawNumDiamond(9);
}
}
The issue is in this line :
dijamant[row][kolona] += count;
if dijamant[row][kolona] is null and count is 2, the result of the string concatenation will be "null2". Try adding the following if statement before to initialize with an empty string :
if (dijamant[row][kolona] == null) {
dijamant[row][kolona] = "";
}
This will get your code working, but there are still things to think about. E.g. you keep setting dijamant[0][0] = "1"; in the loop.
I have to make a program that takes duplicate characters from an input array and prints out a new array with all unique characters.
It all works. Except when characters are taken out, it leaves an empty box at the end of that new array.
public class Deleter {
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
char[] initialInputArray = new char[15];
System.out.println("How many characters do you wish to enter?");
int size = keyboard.nextInt();
while ( size > initialInputArray.length ) {
System.out.println("Error. Enter smaller number.");
size = keyboard.nextInt();
}
if( initialInputArray.length <= 15) {
for ( int counter = 0; counter < size; counter++ ){
initialInputArray[counter] = keyboard.next().charAt(0);
}
{
}
}
deleteRepeats(initialInputArray, size);
//Comeback to print out array
{
for ( int helloWorld = 0 ; helloWorld < size ; helloWorld ++)
System.out.print( initialInputArray[helloWorld] );
}
}
//"deleteReapets" method begins, looking for repeated user inputs
public static char[] deleteRepeats (char[] methodArray, int sizeTwo) {
if (sizeTwo == 0)
return methodArray;
if (sizeTwo == 1)
return methodArray;
int uniqueCharacter = 1;
//Start at the second entered character.
for (int x = 1; x < sizeTwo; ++x) {
int y;
for (y = 0; y < uniqueCharacter; ++y) {
if (methodArray[x] == methodArray[y]) break; // break if we find duplicate.
}
if (y == uniqueCharacter) {
methodArray[uniqueCharacter] = methodArray[x]; // add
++uniqueCharacter; // increment uniqueCharacter...[0,uniqueCharacter) is still "unique char list"
}
}
while ( uniqueCharacter < sizeTwo ) {
methodArray[uniqueCharacter] = 0;
uniqueCharacter++;
}
return methodArray;
}
}
That empty box is the null characters that you added at the end of the array. You are printing them because you are not adjusting size according to the number of unique characters (which can be less than the input size). Since you aren't creating a new array, you don't need to return a char [] from deleteRepeats. Instead, you can return the number of unique characters. That way, the calling program knows how many to print.
If your assignment requires that deleteRepeats return a char[], then you should allocate a new array that has a length exactly equal to uniqueCharacter, copy the unique characters to it, and return that. The calling program can just print that new (and shorter) array, rather than printing the first size elements of the input.
Probably the easiest way would be to make a new array to the size of your array of chars and then copy all of the chars into that. The problem with arrays is that once they have been initialized they can't be re sized. If your are familiar with arrayLists I would recommend using them. But if not try something like this...
int count = 0;
for(int i = 0; i < initialInputArray.size; i++){
count++;
}
char[] newArray = new char[count];
for(int i = 0; i < count; i++){
newArray[i] = initialInputArray[i];
}
I would suggest using a HashSet to remove duplicates and wrapping your char to Character. Something like this:
public static Character[] deleteRepeats (char[] methodArray){
HashSet<Character> set = new HashSet<Character>();
for(int index = 0; index < methodArray.length; index++){
set.add(methodArray[index]);
}
return set.toArray(new Character[set.size()]);
}
So in your main method, what you would do is something like this:
Character[] charArray = deleteRepeats(methodArray);
for(int index = 0; index < charArray.length; index++){
System.out.println(charArray[index]);
}