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]));
}
Related
So I have to print out an array which:
The first cell defines the dimension of the square array. So, I have the input Scanner.
On the first row of the array, every cell has to be the triple of the previous one minus one.
For every next row, every cell has to have the double of the same column of the previous line, plus the number of the column.
For example: if the input of the dimensions is 4, like showArrray(creerArray(4));, then it should print something like:
4 11 32 95
8 23 66 193
16 47 134 389
32 95 270 781
I already coded the part for the input dimension, but I am stuck at trying to figure out how to code this sequence:
public static void showArray() {
}
public static void createArray() {
int square= 0;
int[][] int2D = new int[square][square];
java.util.Scanner input = new Scanner(System.in);
square= input.nextInt();
System.out.println("Enter the dimension of the array:" + square);
int counter=0;
for(int i=0; i<square; i++) {
for(int j=0; j<square; j++){
int2D[i][j]=counter;
counter++;
}
input.close();
}
****i have to start coding the sequence here
}
It's all a matter of where you place your calculations within the for loops to generate the 2D Array, for example:
// Get Array size from User...
Scanner userInput = new Scanner(System.in);
int aryLength = 0; // To hold the square 2D Array Rows and Columns length.
while (aryLength == 0) {
System.out.print("Enter 2D Array square size: --> ");
String len = userInput.nextLine();
/* Is the supplied value valid...
The Regular Expression passed to the String#matches() method
will return boolean true is the variable len only contains
a string representation of a signed or unsigned integer
value. */
if (len.matches("-?\\d+")) {
// Yes it is:
aryLength = Integer.valueOf(len);
}
else {
System.err.println("Invalid numerical value (" + len + ") supplied!");
System.err.println();
}
}
// Declare and initialize the 2D Array
int[][] array = new int[aryLength][aryLength];
int startVal = aryLength; // Used to calculate the first cell of every array Row
// Iterate array Rows...
for (int i = 0; i < array.length; i++) {
// Iterate Columns of each array row...
int cellVal = startVal; // Used for the cell values for all columns in each row
for (int j = 0; j < aryLength; j++) {
array[i][j] = cellVal;
cellVal = ((array[i][j] * 3) - 1); // calculate cell value
}
startVal = startVal * 2; // Calculate first cell value for very row.
}
// Display the 2D Array
System.out.println();
for (int i = 0; i < array.length; i++) {
System.out.println(Arrays.toString(array[i]).replaceAll("[\\[\\]]", ""));
}
You cant change array size in Java please read here once it is created. I suggest you should ask user first before creating the array
Scanner input = new Scanner(System.in);
System.out.print("Enter the dimension of the array:"); // ask user
int square= input.nextInt(); //accept user input here
int[][] int2D = new int[square][square]; //and then create the array
EDIT: You cant put the "square" variable in the print because it hasnt been created yet
Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(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:
###
###
###$
###
###
##$
%##
###
##$
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.
Basically, I need to prompt the user for the rows and columns of an array without asking how many rows and columns there are. How do I improve the following code to do that?
System.out.println("Please input the first set of integers separated by spaces" );
String givenSet1 = console.readLine();
set1 = givenSet1.split(" ");
set1Values = new int[set1.length];
for(int i = 0; i < set1.length; i++)
{
set1Values[i] = Integer.parseInt(set1[i]);
}
while(counter <= set1Values.length)
{
numbers = new int[set1Values.length][];
numbers[counter] = set1Values[counter];
}
for(int a = 0; a < set1Values.length; a++)
{
System.out.println("Please input the set of integers that are to be associated with element " + a + ", separated by spaces" );
String givenSet2 = console.readLine();
set2 = givenSet2.split(" ");
set2Values = new int[set2.length];
numbers[a] = new int[set2Values.length];
System.out.println(numbers[a]);
for(int b = 0; b < set2Values.length; b++)
{
}
}
You can use Array.length() function to return number of elements in an array.
Your question is unclear and it is difficult to understand what you are trying to do from your code but I took a shot in the dark...
It seems as if you want to create a two dimensional array based on the user's input. The total amount of numbers inputted by the user would define the amount of columns in the array, with the user providing a set integers to store as associated numbers for each of those columns. The result would be a two dimensional array as long as the user always entered the same amount of numbers to associate with each column, but just incase I coded it to create a jagged array.
Code:
import java.util.Scanner;
public class Create2DArray {
public static void main(String[] args)
{
int[][] jaggedArray; //declare 2D array
String[] userInput; //declare array for user input
String[] userInput2; //declare array for ints to associate with first input
Scanner input = new Scanner(System.in); //scanner to read
System.out.println("Please input the first set of integers separated by spaces: " );
userInput = input.nextLine().split(" "); //parsing first set of string input
jaggedArray = new int[userInput.length][]; //create 2D array based on no. of columns defined in first set of user input
// array elements will be referenced by x and y, like coordinates.
for (int x = 0; x < jaggedArray.length; x++) //cycle through first set of numbers to prompt for associate numbers
{
System.out.println("Please input the set of integers that are" +
"to be associated with element " + userInput[x] + ", separated by spaces: " );
userInput2 = input.nextLine().split(" "); //parse and store the set to be associated with userInput[x]
jaggedArray[x] = new int[userInput2.length + 1]; //create a new int array in column x of jagged array, +1 to hold userInput[x] then associated values
for (int y = 0; y < jaggedArray[x].length; y++) // cycle through the new array # column x
{
if (y == 0)
jaggedArray[x][y] = Integer.parseInt(userInput[x]); //if y = 0 then copy the "column header" first
else
jaggedArray[x][y] = Integer.parseInt(userInput2[y-1]); // else copy the new elements at position y-1 due to jagged array being +1 more than userInput2 array
}
}
System.out.println();
for (int x = 0; x < jaggedArray.length; x++) //cycling through the array to print it all
{
System.out.print("For integer: " + jaggedArray[x][0] +
" the following integers are associated with it. ");
for (int y = 1; y < jaggedArray[x].length; y++)
{
System.out.print(jaggedArray[x][y] + " ");
}
System.out.println();
}
}
}
Next time please try to provide more information about your desired end results as well as more complete example code. It would be slightly easier to understand your code and requirements if we knew certain things such as what type of objects some of the variables in your example were. The more information the better.
Hopefully this won't be too hard to follow, and it's what you actually wanted.