The code I have now prints out a grid made from an array:
//some code that generates the array gameCards[] = {'a','a','a','a','b','b','b','b'}
//n is the size/length of the array
public String BoardToString(){
int gridCount = 1;
int cardCount = 0;
char[][] showBoard = new char[n/4][4];
while (cardCount < n){
for(int row = 0; row < (n/4); row++){
for(int column = 0; column < 4; column++){
showBoard[row][column] = gameCards[cardCount]; // also how can I use gameCards if it's generated in another method within the same class?
System.out.print("X (" + gridCount + ") ");
gridCount++;
cardCount++;
}
if ((n/4) > 1) System.out.println();
}
}
}
It will print out something like this:
// if n = 8
X(1) X(2) X(3) X(4)
X(5) X(6) X(7) X(8)
The presentation of the grid corresponds to the order of the elements in the original array. If I want to achieve something like this:
a(1) X(2) X(3) X(4)
X(5) X(6) X(7) X(8)
or
a(1) X(2) X(3) X(4)
X(5) b(6) X(7) X(8)
How should I write the loop so it can print out most of the masked grid and only showing 1 actual element (maximum element I need to reveal is 2)?
Basically you have to store coordinates of the card user picked. Then when printing a card check if it is the card user picked. If it is, print its letter instead of an X. Remember first choice and repeat the process for the second card. After second round clear the two cards you stored and repeat.
for(int column = 0; column < 4; column++){
showBoard[row][column] = gameCards[cardCount]; // also how can I use gameCards if it's generated in another method within the same class?
if (pickedRow1 == row && pickedCol1 == column || pickedRow2 == row && pickedCol2 == column) {
System.out.print(CARD_LETTER + " (" + gridCount + ") ");
} else {
System.out.print("X (" + gridCount + ") ");
}
gridCount++;
cardCount++;
}
For your second question. When you generate gameCards in the other method, either pass it to BoardToString as a parameter or you can store it to the instance variable and later access it in the BoardToString method.
Related
Is there a way to populate a 2D Array with unique, nonrandom values? The compiler won't allow something like:
int[][] myArray=new int[5][5];
myArray[0]=new int[] {2, 1, 1, 1, 1};
to happen, and all of the tutorials I've seen on this have related to adding random numbers or populating the array from the start(not applicable to me, as my program depends on user input to know what number values to add). If this isn't possible, is there another method I should be using?
You should use a nested for loop:
for(i=0;i<arr.lenght;i++)
for(j=0;j<arr.lenght;j++)
After doing your nested loop, add something like this:
myArray[i][j]= userInput.next(); //assuming you are using Scanner class
what the nested loop does is iterate through each of the "spaces" the array has and because you are asking the user to input something each time, your array will populate in each "space" with the desired input.
Hope this helps.(ignore my edits, totally misread)
You can fill your 2D Integer (int) Array with either unique values throughout the entire Array or unique values only for each Row of the Array. There are several ways to do this sort of thing but we'll just stick with basic methods. The code is well commented:
User fills 2D Integer Array with Unique Rows only:
// Setup for Keyboard input to Console.
Scanner input = new Scanner(System.in);
// System Line Separator used in console display.
String ls = System.lineSeparator();
// Declare and initialize a 2D Object Array.
// We need to use Object so that all initialized
// elements will be null rather than 0 since 0
// could be supplied and will need to be checked
// for Unique. Since a 2D int array by default
// initializes all elements to 0, a supplied 0
// will never be considered Unique.
Object[][] myArray = new Object[5][5];
// Have User fill our 2D Array...
for (int row = 0; row < myArray.length; row++) {
// Display the Row User will be on to fill.
System.out.println(ls + "Enter values for Row #" + (row+1) +
" of " + myArray.length);
// Allow User to fill each column of the current Row...
for (int column = 0; column < myArray[row].length; column++) {
// Flag to indicate Uniqueness.
boolean unique = false;
// Integer variable to hold what the User enters in console
int value = 0;
// Continue looping to ensure the User supplied a proper
// integer value which is unique to the current 2D Array
// Row only.
while (!unique) {
// Display the Column User will be on to fill.
System.out.print("Column #" + (column+1) + " value: --> ");
// Trap User entries that are not Integer values. If any alpha
// characters are supplied with the value then an exception is
// automatically thrown which we trap.
try {
// Get input from User...
value = input.nextInt();
} catch (Exception ex) {
// Inform the User of an improper entry if an exception was thrown.
System.err.println("You must supply an Integer value. Try again...");
input.nextLine(); // Clear Scanner buffer
// Allow User to try another entry for the same Column
continue;
}
// See if the supplied value is already contained within the
// current array Row...
for (int j = 0; j < myArray[row].length; j++) {
// Stop checking if we hit null. Nothing there yet.
if (myArray[row][j] == null) {
unique = true;
break;
}
// If a row's column element equals supplied value...
else if ((int)myArray[row][j] == value) {
// Value is not Unique
unique = false;
System.err.println("Value is not unique to Row #" +
(row+1) + " - Try Again...");
break; // Break out of checking early
}
// The supplied value is unique.
else {
unique = true;
}
}
}
//Place the value into the current
// Column for the current Row
myArray[row][column] = value;
}
}
// Convert the 2D Object Array to a 2D int Array
int[][] intArray = new int[myArray.length][myArray[0].length];
for (int i = 0;i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
intArray[i][j] = (int)myArray[i][j]; // Cast to int
}
}
// Display the 2D Array in Console Window...
System.out.println(ls + "2D Integer Array Contents:");
for (int i = 0; i < intArray.length; i++) {
System.out.println("Row #" + (i+1) + ": " + Arrays.toString(intArray[i]));
}
}
User fills 2D Integer Array with Unique values throughout the entire Array:
// Setup for Keyboard input to Console.
Scanner input = new Scanner(System.in);
// System Line Separator used in console display.
String ls = System.lineSeparator();
// Declare and initialize a 2D Object Array.
// We need to use Object so that all initialized
// elements will be null rather than 0 since 0
// could be supplied and will need to be checked
// for Unique. Since a 2D int array by default
// initializes all elements to 0, a supplied 0
// will never be considered Unique.
Object[][] myArray = new Object[5][5];
// Have User fill our 2D Array...
for (int row = 0; row < myArray.length; row++) {
// Display the Row User will be on to fill.
System.out.println(ls + "Enter values for Row #" + (row+1) +
" of " + myArray.length);
// Allow User to fill each column of the current Row...
for (int column = 0; column < myArray[row].length; column++) {
// Flag to indicate Uniqueness.
boolean unique = false;
// Integer variable to hold what the User enters in console
int value = 0;
// Continue looping to ensure the User supplied a proper
// integer value which is unique to the ENTIRE 2D Array.
while (!unique) {
// Display the Column User will be on to fill.
System.out.print("Column #" + (column+1) + " value: --> ");
// Trap User entries that are not Integer values. If any alpha
// characters are supplied with the value then an exception is
// automatically thrown which we trap.
try {
// Get input from User...
value = input.nextInt();
} catch (Exception ex) {
// Inform the User of an improper entry if an exception was thrown.
System.err.println("You must supply an Integer value. Try again...");
input.nextLine(); // Clear Scanner buffer
// Allow User to try another entry for the same Column
continue;
}
// Flag to hold when a match is found. This flag will allow
// us to break out the the for loops faster
boolean match = false;
// See if value is already contained within the array.
// Iterate Rows...
for (int i = 0; i < myArray.length; i++) {
// Iterate the Columns for each Row...
for (int j = 0; j < myArray[i].length; j++) {
// Stop checking if we hit null. Nothing there yet.
if (myArray[i][j] == null) {
break;
}
// If a row's column element equals supplied value...
else if ((int)myArray[i][j] == value) {
match = true; // A match was detected - Not Unique
System.err.println("Value is not Unique - Try Again...");
break; // Break out of checking early
}
}
if (match) { break; } // Break out of outer loop is there was a match
}
unique = !match; // unique flag is to be oposite of what match contains
}
myArray[row][column] = value; // Add supplied value to array
}
}
// Convert the 2D Object Array to a 2D int Array
int[][] intArray = new int[myArray.length][myArray[0].length];
for (int i = 0;i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
intArray[i][j] = (int)myArray[i][j]; // Cast to int
}
}
// Display the 2D Array...
System.out.println(ls + "2D Integer Array Contents:");
for (int i = 0; i < intArray.length; i++) {
System.out.println("Row #" + (i+1) + ": " + Arrays.toString(intArray[i]));
}
I made a 2 dimensional array like this:
char Grid[][] = {
{'#','#','#'}
{'#','#','#'}
{'#','#','#'}
}
and displayed it with this:
for (int row = 0; row < Grid.length; row++) {
for (int column = 0; column < Grid[row].length; column++) {
System.out.print(Grid[row][column]);
}
System.out.println();
}
I want to be able to simple adjust the elements in the array, like adding and removing elements. Since basic java (for some reason) doesn't seem to have any predefined functions to do this, i tried using the ArrayUtils class from common langs. I found a couple methods in the docs including "Add", "insert", and "remove" and tried something like this:
ArrayUtils.insert(Scene, Grid, 2); //(With "Scene" being the class name)
But as expected, it didn't work.
On another website, i read something about cloning the array, but i don't think this is the solution to my problem since i want to be able to move around an ASCII character, and i don't want to create a new array each time i move it.
EDIT: To be clear, i want to be able to either CHANGE the index value's or quickly remove then and place another on the exact spot.
arrays are basic types and are not used to add elements, for these operations ArrayList and depending if there is many inserts and deletes at any places LinkedList may be more convenient. ArrayUtils.insert should return a new array instance doing a copy of initial array.
Once created an array in java is with fixed length so in your case after you have used the Array Inicializer you end up with an array with length 3, having elements of type char array where each of them is with fixed length of 3 as well. To replace a given value all you need is to assign the new value to the proper indexes like :
Grid[i][j] = 'new character value';
As I've already said since the size is fixed you can not add new values to it, unless u copy the entire array in a new array of size (length +1) and place the new value on the desired position. Simple code demonstrating that:
private static void add(char[][] grid, int row, int column, char value) {
if (row < 0 || row > grid.length) {
throw new ArrayIndexOutOfBoundsException("No such row with index " + row + " inside the matrix."); // you are trying to insert an element out of the array's bounds.
}
if (column < 0 || column > grid[row].length) {
/*
* An array in Java is with fixed length so you should keep the index inside the size!
*/
throw new ArrayIndexOutOfBoundsException("Index " + column + " does not exists in the extended array!"); // you are trying to insert an element out of the array's bounds.
}
boolean flag = false; //indicates that the new element has been inserted.
char[] temp = new char[grid[row].length + 1];
for (int i = 0; i < temp.length; i++) {
if (i == column) {
temp[i] = value;
flag = true;
} else {
temp[i] = grid[row][i - (flag ? 1 : 0)];
}
}
grid[row] = temp; //assign the new value of the whole row to it's placeholder.
}
To remove an element from the array you would have to make a new array with size[length - 1], skip the element you would like to remove and add all the others. Assign the new one to the index in the matrix then. Simple code:
private static void remove(char[][] grid, int row, int column) {
if (row < 0 || row > grid.length) {
throw new ArrayIndexOutOfBoundsException("No such row with index " + row + " inside the matrix."); // you are trying to insert an element out of the array's bounds.
}
if (column < 0 || column > grid[row].length) {
throw new ArrayIndexOutOfBoundsException("No such column with index " + column + " at row " + row + " inside the matrix."); // you are trying to insert an element out of the array's bounds.
}
boolean flag = false; //indicates that the element has been removed.
char[] temp = new char[grid[row].length - 1];
for (int i = 0; i < temp.length; i++) {
if (i == column) {
flag = true;
}
temp[i] = grid[row][i + (flag ? 1 : 0)];
}
grid[row] = temp; //assign the new value of the whole row to it's placeholder.
}
If I define a method called print(char[][] grid) and put the code you use for printing then i'm able to do these tests:
add(Grid, 2, 3, '$'); //Add an element.
print(Grid);
System.out.println();
remove(Grid, 2, 0); // Remove an element.
print(Grid);
System.out.println();
Grid[0][0] = '%'; // Change an element's value.
print(Grid);
And the output is as follows:
###
###
###$
###
###
##$
%##
###
##$
I'm trying to make a Java program that uses the input value from a user to calculate and list the products of two numbers up to the entered number. Like if a user enters 2, the program should calculate the products between the two numbers (1 *1, 1*2, 2*1, 2*2) stores the products in a two-dimensional array, and list the products. I'm not sure that I totally understand arrays and so I feel as though my code is problem not right in many instances, can someone please tell me what I should do to my current code to make it work properly. Thanks in advance! :)
import java.util.Scanner;
public class ProductTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inputString;
char letter = 'y';
// Prompt the user to enter an integer
while(letter != 'q') {
System.out.print("Enter a positive integer: ");
int integer = input.nextInt();
// Create an two-dimensional array to store products
int[][] m = new int[integer][3];
for (int j = 1; j <= m.length; j++) {
m[j][0] = input.nextInt();
m[j][1] = input.nextInt();
m[j][2] = input.nextInt();
}
// Display the number title
System.out.print(" ");
for (int j = 1; j <= m.length; j++)
System.out.print(" " + j);
System.out.println("\n--- ");
// Display table body
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
// Prompt the user to either continue or quit
System.out.print("Enter q to quit or any other key to continue: ");
String character = input.nextLine();
inputString = input.nextLine();
letter = inputString.charAt(0);
}
}
}
You can achieve your multiplication table by iterating over 2 counter variables as you already did in your output
// Display table body
// loops running out of bounds (until m.length + 1 instead of m.length-1)
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) { // missed to increment j here
System.out.printf("%4d", i * j);
}
System.out.println();
}
Arrays should be based on 0, that means an array with 3 fields has the indexes 0, 1, 2. So the last index is length-1. Your condition <=m.length+1 runs out of bounds. index<length will work since 2 is less than 3, but not 3 less than 3.
You have also a typo: In the inner loop you are doing an increment of i instead of j, so the loop will run infinite.
Try to create an outer and inner loop as you did, but with start index 0 and end condition index<inputValue. Calculate multiTable[index1][index2] = (1+index1)*(1+index2).
Then do a similar loop and print the array fields. You don't need to use an array, you could output directly as you did. But you wanted to practice handling arrays.
Since you want to learn and understand, I don't like just to write the code. imagine an array with 3 fields having the indexes 0, 1, 2:
index 0 | 1 | 2
value 1 | 2 | 3
Now you would check the length at first, that's 3. You start with 0 and count while the counter does not reach the length since the zero based index is 1 below our natural order (0,1,2 vs. 1,2,3). That is the case as long the index is below the length, meaning index<length.
Try this logic (pseudo code). To simplify the problem we include the 0 in our product table. So we get 0*0, 0*1, 0*2... Doing so, we do not have to ignore index 0 or to calculate between index 0 should represent value 1.
maxNumber = userInput()
outer loop idx1 from 0 to maxNumber
inner loop idx2 from 0 to maxNumber
array[idx1][idx2] = (idx1) * (idx2)
end loop
end loop
Do the same to dump your generated array to screen.
First get it running. Afterwards you could try to alter the logic, so that it shows you only numbers from 1 to max.
I want to make a list going to n numbers depending on user input. I then want to put a second number in each place and print the entire table. As for testing I have tried with a length 4 and numbers 1,2,3,4 but I get a error: ArrayIndexOutOfBounds. I wanted it to print 1,2,3,4.
Scanner keyboard = new Scanner (System.in);
System.out.println("Whats the length of the table?");
int lengde = keyboard.nextInt();
int[] minTabell = new int[lengde];
for (int i =1; i <= lengde+ 1; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
System.out.println(minTabell);
keyboard.close();
Indexes in Java arrays are 0-based, while your for-loop starts from 1. So,
for (int i =1; i <= lengde+ 1; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
should be
for (int i =0; i < lengde; i++) {
// ^ ^^^^^^^^
System.out.println((i+1) + (" give a number"));
// ^^^
minTabell[i] = keyboard.nextInt();
}
As for printing the content of the array, I suggest you use
for (int i : minTabell)
System.out.println(i);
In Java array indexing starts at 0. The first element is positioned at minTabel1[0]. Your for-loop runs from 1 to lengde + 1, which means that you will try to fill a position outside of the array.
The first element of an array has the index 0. The last valid index of your array is lengde-1.
Try this:
for (int i=0; i < lengde; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
To print the array, i suggest the following:
System.out.println(Arrays.toString(minTabell));
I have made a program that outputs the number of repeats in a 2D array. The problem is that it outputs the same number twice.
For example: I input the numbers in the 2D array through Scanner: 10 10 9 28 29 9 1 28.
The output I get is:
Number 10 repeats 2 times.
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 9 repeats 2 times.
Number 1 repeats 1 times.
Number 28 repeats 2 times.
I want it so it skips the number if it has already found the number of repeats for it. The output should be:
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 1 repeats 1 times.
Here is my code:
import java.util.Scanner;
public class Repeat
{
static Scanner leopard = new Scanner(System.in);
public static void main(String [] args)
{
final int ROW = 10; //Row size
final int COL = 10; //Column size
int [][] num = new int[ROW][COL];
int size;
//Get input
size = getData(num);
//Find repeat
findRepeats(num, size);
}
public static int getData(int [][] num)
{
int input = 0, actualSize = 0; //Hold input and actualSize of array
System.out.print("Enter positive integers (-999 to stop): ");
//Ask for input
for(int i = 0; i < num.length && input != -999; i++)
{
for(int j = 0; j < num[i].length && input != -999; j++)
{
input = leopard.nextInt();
//Check if end
if(input != -999)
{
num[i][j] = input;
actualSize++;
}
}
}
System.out.println();
return actualSize;
}
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 0, row = 0, col = 0;
for(int x = 0; x < size; x++)
{
//Set to number
findNum = num[row][col];
//Loop through whole array to find repeats
for(int i = 0; i < num.length; i++)
{
for(int j = 0; j < num[i].length; j++)
{
if(num[i][j] == findNum)
total++;
}
}
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 0;
}
}
}
I know why it is doing it, but I cannot figure out how to check if the number has already been checked for it to skip that number and go to the next number. I cannot use any classes or code that is not used in the code.
Since you cannot use anything other than this, lets say, basic elements of Java consider this:
Make another temporary 2D array with two columns (or just two separate arrays, personally I prefer this one). On the start of the algorithm the new arrays are empty.
When you take a number (any number) from the source 2D structure, first check if it is present in the first temporary array. If it is, just increment the value (count) in the second temporary array for one (+1). If it is not present in the first tmp array, add it to it and increase the count (+1) in the second at the same index as the newly added number in the first (which should be the last item of the array, basically).
This way you are building pairs of numbers in two arrays. The first array holds all your distinct values found in the 2D array, and the second one the number of appearances of the respective number from the first.
At the and of the algorithm just iterate the both arrays in parallel and you should have your school task finished. I could (and anyone) code this out but we are not really doing you a favor since this is a very typical school assignment.
It's counting the number two times, first time it appears in the code and second time when it appears in the code.
To avoid that keep a system to check if you have already checked for that number. I see you use check int array but you haven't used it anywhere in the code.
Do this,
Put the number in the check list if you have already found the count of it.
int count = 0;
check[count] = findNum;
count++;
Note: You can prefill you array with negative numbers at first in order to avoid for having numbers that user already gave you in input.
Next time in your for loop skip checking that number which you have already found a count for
for(int x = 0; x < size; x++) {
findNum = num[row][col];
if(check.containsNumber(findNUm)) { //sorry there is no such thing as contains for array, write another function here which checks if a number exists in the array
//skip the your code till the end of the first for loop, or in other words then don't run the code inside the for loop at all.
}
}
Frankly speaking I think you have just started to learn coding. Good luck! with that but this code can be improved a lot better. A piece of advice never create a situation where you have to use 3 nested for loops.
I hope that you understood my solution and you know how to do it.
All answers gives you some insight about the problem. I try to stick to your code, and add a little trick of swap. With this code you don't need to check if the number is already outputted or not. I appreciate your comments, structured approach of coding, and ask a question as clear as possible.
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 1, row = 0, col = 0;
int [] check = new int[size];
while(row < num.length && col < num[0].length)
{
//Set to number
findNum = num[row][col];
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Loop through whole array to find repeats
for(int i = row; i < num.length; i++)
{
for(int j = col; j < num[i].length; j++)
{
if(num[i][j] == findNum) {
total++;
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
if(row < num.length - 1 && col < num[0].length -1)
num[i][j] = num[row][col];
}
}
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 1;
}
}
you can use a HashMap to store the result. It Goes like this:
// Create a hash map
HashMap arrayRepeat = new HashMap();
// Put elements to the map
arrayRepeat.put(Number, Repeated);