I want to create an multidimensional array that will count.
This is the code I have so far and don't know where to go from here. When I print this out I want it to look like 0,1,2,3,4,5,6,7,8,9,10,etc.
public static void main(String[] args) {
int car[][] = new int[4][4];
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
System.out.print(car[row][col] + ",");
}
System.out.println();
}
}
you're creating empty array so every field has value 0
try this:
public static void main(String[] args) {
int car[][] = new int[4][4];
int index = 0;
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = index++;
System.out.print(car[row][col] + ",");
}
System.out.println();
}
}
You need to set the values before printing them
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = row * 4 + col;
System.out.print(car[row][col] + ",");
}
System.out.println();
}
But it's silly and pointless to use a multi-dimensional array like this.In my experience, Multi-dimensional arrays are useful in a much more limited scope than how people play with them when they are learning.
Use this:
public static void main(String[] agrs) {
int car[][] = new int[4][4];
int i = 0;
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = i++;
System.out.print(car[row][col] + ",");
}
}
}
Related
How should I generate a 4X4 2D array table with every element different?
Here's my code:
public class Game {
public static void main(String[] args) {
int gameboard[][] = new int[4][4];
for (int row=0; row < gameboard.length; row++) {
for (int col=0; col < gameboard[row].length; col++) {
gameboard[row][col] = ((int)(1+Math.random() * 16));
System.out.printf("%-4d",gameboard[row][col]);
}
System.out.println();
}
}
}
Solution 1 :
public static void main(String[] s1) throws Exception {
int gameboard[][] = new int[4][4];
Set<Integer> mySet = new HashSet<>();
for (int row = 0; row < gameboard.length; row++) {
for (int col = 0; col < gameboard[row].length; col++) {
int randNum = (int) (1 + Math.random() * 16);
while (mySet.contains(randNum)) {
randNum = (int) (1 + Math.random() * 16);
}
mySet.add(randNum);
gameboard[row][col] = randNum;
System.out.printf("%-4d", gameboard[row][col]);
}
System.out.println();
}
}
Here in each iteration we check if the random number generated is present in the set. If it is present then we loop until we get a different random number that is not present in the set.
Solution 2 :
List<Integer> myList = IntStream.range(1, 17).boxed().collect(Collectors.toList());
Collections.shuffle(myList);
for (int row = 0; row < gameboard.length; row++) {
for (int col = 0; col < gameboard[row].length; col++) {
gameboard[row][col] = myList.get(row * gameboard.length + col);
System.out.printf("%-4d", gameboard[row][col]);
}
System.out.println();
}
Here we generate a list of numbers and then shuffle it using Collections.shuffle(). Now we iterate over the multi-dimensional array and assign the values of the list to the array.
You just need to put a control after like:
int a == gameboard[row][col];
for (int row=0; row < gameboard.length; row++) {
for (int col=0; col < gameboard[row].length; col++) {
gameboard[row][col] = ((int)(1+Math.random() * 16));
if(gameboard[row][col] == a){
col = col - 1;
}
}
}
You could use a Set first to get no duplicates, and then a List to access them easily
Set<Integer> set = new LinkedHashSet<>();
int gameboard[][] = new int[4][4];
while(set.size() != 4*4){
set.add((int)(1+Math.random() * 16));
}
List<Integer> list = new ArrayList<>(set);
for (int row=0; row < gameboard.length; row++) {
for (int col=0; col < gameboard[row].length; col++) {
gameboard[row][col] = list.get(row*gameboard.length + col);
System.out.printf("%-4d",gameboard[row][col]);
}
System.out.println();
}
}
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length + amount; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount < original.length) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
Hi,
I am trying to write a method that will shift the elements in my 2-D array to the left by some arbitrary amount. I don't want to loop the values back around, but instead fill the empty arrays with some fill_value which is already predefined. And if the shift amount is more than the orignial length, I would just return an image with only fill_value. However, this function is throwing an arrayindexoutofbound Error. But I can't think of how I should change my for loop to fix the error. Any help is appreciated! Thank you!
I believe it's because in your second outer for loop, the condition is cols < length + amount, so it will continue past the edge of the array if amount > 0. You could step through your code with a debugger and see exactly where it's going out of bounds.
The error is occurring because of following line:
shifted[cols][rows] = original[cols - amount][rows];
When cols=0, rows=0, amount=2 (say), it is trying to access original[-2][0] which does not exist.
Instead you may use following:
public class overflow1 {
static int a[][] = {{1,2,3,4,5,6},{2,3,4,5,6,7},{3,4,5,6,7,8}, {4,5,6,7,8,9}, {5,6,7,8,9,10}, {6,7,8,9,10,11}};
static int b[][] ;
static int FILL_VALUE =0;
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length ; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount >=0) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
public static void main(String[] arggs) {
b=shift(a,2);
System.out.println("Original array:");
for(int i=0; i<a.length; i++){
for (int j=0; j<a[i].length; j++){
System.out.print(a[i][j]+ ":");
}
System.out.println();
}
System.out.println("After shift by 2 array:");
for(int i=0; i<b.length; i++){
for (int j=0; j<b[i].length; j++){
System.out.print(b[i][j]+ ":");
}
System.out.println();
}
}
}
Here is the output for the sample:
Original array:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:
5:6:7:8:9:10:
6:7:8:9:10:11:
After shift by 2, array:
0:0:0:0:0:0:
0:0:0:0:0:0:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:
I need to make a multiplication table that shows 1 * 1 up to 12 * 12. I have this working but it needs to be in 13 columns in a format that looks like the diagram below, really appreciate any help.
1 2 3 4 5 6 7 8 9 10 11 12
1 1 2 3 4 5 ...
2 2 4 6 8 10 ....
3
4
5
6
...
Code so far:
public class timetable {
public static void main(String[] args) {
int[][] table = new int[12][12];
for (int row=0; row<12; row++){
for (int col=0; col<12; col++){
table[row][col] = (row+1) * (col+1);
}
}
for (int row = 0; row < table.length; row++) {
for (int col = 0; col < table[row].length; col++) {
System.out.printf("%6d", table[row][col]);
}
System.out.println();
}
}
}
Print column headings before printing the table, and print row headings at the start of each row. You can use the code below.
int[][] table = new int[12][12];
for (int row=0; row<12; row++){
for (int col=0; col<12; col++){
table[row][col] = (row+1) * (col+1);
}
}
// Print column headings
System.out.printf("%6s", "");
for (int col = 0; col < table[0].length; col++) {
System.out.printf("%6d", col+1);
}
System.out.println();
for (int row = 0; row < table.length; row++) {
// Print row headings
System.out.printf("%6d", row+1);
for (int col = 0; col < table[row].length; col++) {
System.out.printf("%6d", table[row][col]);
}
System.out.println();
}
This only prints 9x9 timetable, if you need to change it 12x12, then just change the numbers in the code from "9" to "12", and add more "----" lines in the system output to match it
This includes " * |" and "----" ...
Thought this might be helpful for anyone else
Output:
9x9 Timetable
public class timetable2DArray
{
public static void main(String[] args)
{
int[][] table = new int[9][9];
for (int row=0; row<9; row++)
{
for (int col=0; col<9; col++)
{
table[row][col] = (row+1) * (col+1);
}
}
// Print column headings
System.out.print(" * |");
for (int col = 0; col < table[0].length; col++)
{
System.out.printf("%4d", col+1);
}
System.out.println("");
System.out.println("------------------------------------------");
for (int row = 0; row < table.length; row++)
{
// Print row headings
System.out.printf("%4d |", row+1);
for (int col = 0; col < table[row].length; col++)
{
System.out.printf("%4d", table[row][col]);
}
System.out.println();
}
}
}
int [][] A = new int[5][5];
int [][] B = new int[5][5];
for (int row = 0; row < A.length; row++) {
System.out.println();
for (int col = 0; col < A.length; col++) {
B[row][col] = (row+1)*(col+1);
System.out.print("\t");
System.out.printf("%2d", B[row][col]);
}
}
You could implement a timesTable() method. Here's my code, modify it anyway you would like.
//main driver
public static void main(String[] args) {
int[][] data; //declaration
data = timesTable(4,6); //initialisation
for (int row = 0; row < data.length ; row++)
{
for (int column = 0; column < data[row].length; column++)
{
System.out.printf("%2d ",data[row][column]);
}
System.out.println();
}
}
//method
public static int[][] timesTable(int r, int c)
{
int [][] arr = new int[r][c];
for (int row = 0; row < arr.length ; row++)
{
for (int column = 0; column < arr[row].length; column++)
{
arr[row][column] = (row+1)*(column+1);
}
}
return arr;
}
I loaded a two dimensional array from a txt file. I need the program to randomly display 75% and 25% of the array separately. I tried using Math.random but it change the numbers to display from 0 to 1. I will be using the numbers in further calculations. I have enclosed the whole code. The dataSplit method is where I separate the array. The txt file that I am using in this example is for testing purposes only. I actually have a much larger file.
Thank you in advance for your help,
Avi
p.s. I am starting the column count from 1 because column 1 is to be ignored.
This is the txt file
1 6 7 8
2 9 10 11
3 12 13 14
Below is the code
package tester;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Random;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner inFile = new Scanner(new FileReader("one.txt"));
float [][] glassdata = new float[3][4];
loadArray(glassdata, inFile);
displayArray(glassdata);
System.out.println("\n***************\n");
normalizingVector(glassdata);
System.out.println("\n***************\n");
dataSplit(glassdata);
}
public static void loadArray(float [][] g, Scanner inFile)
{
for(int row = 0; row < g.length; row++)
{
for(int col = 0; col < g[row].length; col++)
{
g[row][col] = inFile.nextFloat();
}
}
}
public static void displayArray(float [][] g)
{
for(int row = 0; row < g.length; row++)
{
for(int col = 1; col < g[row].length; col++)
{
System.out.print(g[row][col] + " ");
}
System.out.println();
}
}
public static void normalizingVector(float [][] g)
{
float temp1 = 0;
float temp2 = 0;
for (int row = 0; row < g.length; row++)
{
for(int col = 1; col < g[row].length; col++)
{
while(col < g[row].length)
{
temp1 = temp1 + (float) Math.pow(g[row][col], 2);
col++;
}
col = 1;
temp1 = (float) Math.sqrt(temp1);
while(col < g[row].length)
{
temp2 = (g[row][col]) / temp1;
System.out.print(temp2 + " ");
col++;
}
}
System.out.println();
temp1 = 0;
temp2 = 0;
}
}
public static void dataSplit(float [][] g)
{
int row;
int col;
for(row = 0; row < g.length; row++)
{
for(col = 1; col < g[row].length * 0.75; col++)
{
System.out.print(g[row][col] + " ");
}
System.out.println();
}
System.out.println("*******!##$$*************");
for(row = 0; row < g.length; row++)
{
for(col = 2; col < g[row].length * 0.25; col++)
{
System.out.print(g[row][col] + " ");
}
System.out.println();
}
}
}
I have to add the votes per state of the 2008 elections on a 2 dimensional array, but when I run the code it sums only the first row and then keeps adding itself to the previous sum 51 times to the right side like this:
State Obama McCain Other Total by state
Alabama 813479 1266546 19794 2099819 2426016 72985 etc...
Alaska 123594 193841 8762 2099819 2426016 72985 etc...
But i needed to add the total votes on each state only once per row.
public static void main(String[] args) throws IOException
{
// TODO code application logic here
File election = new File("voting_2008.txt");
Scanner sc = new Scanner(election);
String[] states = new String[51];
int[][]votes = new int[51][4];
int[] Totalbystate = new int[votes.length];
for (int s=0; s < 51; s++)
{
states[s] = sc.nextLine();
}
for(int c=0; c < 3; c++)
{
for(int s=0; s < 51; s++)
{
votes[s][c] = sc.nextInt();
}
}
Formatter fmt = new Formatter();
fmt.format("%20s%12s%12s%12s%21s", "State", "Obama", "McCain", "Other", "Total by state");
System.out.println(fmt);
for (int s=0; s < 51; s++)
{
fmt = new Formatter();
fmt.format("%20s", states[s]);
System.out.print(fmt);
for(int c=0; c < 3; c++)
{
fmt = new Formatter();
fmt.format("%12d", votes[s][c]);
System.out.print(fmt);
}
int sum =0;
for(int row=0; row < votes.length; row++)
{
for (int col=0; col < votes[row].length; col++)
{
sum = sum + votes[row][col];
}
fmt = new Formatter();
fmt.format("%21d", sum);
System.out.print(fmt);
}
System.out.println();
}
}
but when I run the code it sums only the first row and then keeps adding itself to the previous sum 51 times to the right side like this:
Look at your code:
int sum =0;
for(int row=0; row < votes.length; row++)
{
for (int col=0; col < votes[row].length; col++)
{
sum = sum + votes[row][col];
}
fmt = new Formatter();
fmt.format("%21d", sum);
System.out.print(fmt);
}
Look at where you're setting sum to 0. Now think about where you should be setting it to 0...