Convert two 1D arrays into single 2D array - java

I have 2 1d arrays and i am trying to populate them into a single 2d array in JAVA.
For instance:
a[] = {2,7}
b[] = {9,1}
The results should then be:
result[][] = {{2,9}, {7,1}}
This is my code
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Test Cases:\t");
int t = sc.nextInt();
int[] a;
int[] b;
int i, j, x;
for (int k = 0; k < t; k++) {
System.out.println("Enter 1st Array Limit:\t");
int len = sc.nextInt();
System.out.println("Enter 2nd Array Limit:\t");
int len1 = sc.nextInt();
a = new int[len];
b = new int[len1];
System.out.println("Enter Sum Value");
x = sc.nextInt();
System.out.println("Enter " + len + " elements:\t");
for (i = 0; i < len; i++) {
a[i] = sc.nextInt();
}
System.out.println("Enter " + len1 + " elements:\t");
for (j = 0; j < len1; j++) {
b[j] = sc.nextInt();
}
int [][] c = new int[len][2];
for (i = 0; i < len; i++) {
for (j = 0; j < len1; j++) {
if (a[i] + b[j] == x) {
for(int l = 0; i < a.length; i++){
c[l][0] = a[i];
c[l][1] = b[j];
}
}
}
}
System.out.println(Arrays.deepToString(c));
}
}
}
This still produces wrong output
i want to find Find all pairs with a given sum

int[] a = {2,7};
int[] b = {9,1};
int[][] c = new int[a.length][2];
for(int i = 0; i < a.length; i++){
c[i][0] = a[i];
c[i][1] = b[i];
}
should do the trick

Related

Out of bounds exception in matrix multiplication [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I wrote this code.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please enter the rows \"then\" columns of the first array: ");
int a = console.nextInt();
int b = console.nextInt();
int[][] arr1 = new int[a][b];
System.out.println("Please enter the rows \"then\" columns of the second array: ");
int c = console.nextInt();
int d = console.nextInt();
int[][] arr2 = new int[c][d];
if (b != c) {
System.out.println("these two matrices can't be multiplied!!");
} else {
int[][] mult = new int[a][c];
System.out.println("Please enter the elements of the first array : ");
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
arr1[i][j] = console.nextInt();
}
}
System.out.println("Please enter the elements of the second array : ");
for (int i = 0; i < c; i++) {
for (int j = 0; j < d; j++) {
arr2[i][j] = console.nextInt();
}
}
int sum = 0;
for (int i = 0; i < a; i++) {
for (int j = 0; j < d; j++) {
for (int k = 0; k < c; k++) {
sum += arr1[i][k] * arr2[k][j];
mult[i][j] = sum;
}
sum = 0;
}
}
for(int i=0;i<a;i++){
for(int j=0;j<d;j++) {
System.out.print(mult[i][j] + " ");
}
System.out.println("");
}
}
}
}
and when I run it, it says java.lang.ArrayIndexOutOfBoundsException.
I don't know why, Thanks for helping.
From what I see, here might be the problem: int[][] mult = new int[a][c], it should be new int[a][d]
P/s: Would be nicer if you can format the first part of your code

Randomly place 1D string array into 2D char array

I'm trying to randomly place 1D string array into 2D char array but I'm having issues with my for-loop.
userWords is 1D array of String while puzzleBoard is a 2D array of char.
I've tried
for(int i=0; i<userWords.length;i++) {
puzzleBoard[r++] = userWords[i].toCharArray();
}
but it's not placing it randomly like I want it to
So I tried
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
but it's printing only 3 char instead of the 3 strings of char into the char array.
I've also tried
puzzleBoard[r][c] = userWords[i].toCharArray();
instead of
puzzleBoard[r][c] = userWords[i].charAt(i);
But it display error "cannot convert from char[] to char"
Thank you
Full Code
public static void main(String[] args) {
String[] userWords = new String[3];
Methods.userInput(userWords); //ask user for input
Methods.fillPuzzle(puzzleBoard); //fill the puzzle with random char
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
Methods.printPuzzle(puzzleBoard); //print out the puzzle
}//end main
public static void printPuzzle(char a[][]) {
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.print((i+1));
System.out.println();
}
}//end printPuzzle
public static void fillPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = '*';
}
}
}//end fillPuzzle
public static void userInput(String a[]) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < a.length;i++) {
System.out.println((i+1) + ". enter word:");
a[i] = input.next().toUpperCase();
}
}//end userInput
You can try this one:
for (int i = 0; i < userWords.length; i++) {
int r = rand.nextInt(puzzleBoard.length);
int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
And you should add something that detects whether there is already a word at this position, otherwise you would overwrite it if the random numbers point to a location where is already written a word.
I think you should use 2 for-loops because you want to select first the string and next the characters in the string.
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}

Creating a matrix from a text file - Java

I have this text file:
2
2
12
13
23
24
49
59
69
79
the first two numbers should be the rows and columns of the matrix, which is 2x2 in this case. My issue that I'm trying to get around is finding a way to include a second 2D array that holds the second matrix.
my code:
Scanner fileInput = new Scanner(new File("input1.txt"));
int n1 = fileInput.nextInt();
int n2 = fileInput.nextInt();
System.out.print("matrix is " + n1 + "x" + n2 +"\n");
int [][] firstMatrix = new int [n1][n2];
int [][] secondMatrix = new int [n1][n2];
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
firstMatrix[i][j] = fileInput.nextInt();
}
}
}
System.out.println("Matrices: ");
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.println(firstMatrix[i][j]);
}
}
it only prints the following:
12
13
23
24
How do I make it read the next four lines of integers from the file? It would also be helpful to understand how I can make it look something like this:
12 13
23 24
EDIT: This approach seemed to help with the last question:
for(int i=0; i<n1; i++)
{
for(int j=0; j<n2; j++)
{
System.out.print(firstMatrix[i][j] + " " );
//System.out.print(secondMatrix[i][j] + " ");
}
System.out.println();
}
The only problem I'm facing now is being able to include the four other integers and turn them into a matrix.
You can group them to 1 array:
int matrixNumb = 2; // number of matrix
int [][][] matrix = new int [matrixNumb][n1][n2];
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
matrix [h][i][j] = fileInput.nextInt(); // read from file
}
}
}
}
System.out.println("Matrices: ");
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.print(matrix[h][i][j]);
System.out.print("\t"); //How do you want to separate columns?
}
System.out.print("\r\n"); //How do you want to separate rows?
}
System.out.println(); //How do u want to print next matrix?
}
I have not compiled or run it, but hope it help.
You can just read data for the two arrays from file sequentially, like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
private static void readMatrix(final Scanner scanner, final int[][] matrix) {
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[i].length; ++j) {
if (scanner.hasNextInt()) {
matrix[i][j] = scanner.nextInt();
}
}
}
}
private static void displayMatrix(final int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(final String... args) throws FileNotFoundException {
final Scanner scanner = new Scanner(new File("input.txt"));
final int n1 = scanner.nextInt();
final int n2 = scanner.nextInt();
System.out.print(String.format("The matrix is %d x %d \n", n1, n2));
final int[][] firstMatrix = new int[n1][n2];
final int[][] secondMatrix = new int[n1][n2];
System.out.println("Reading data to first matrix");
readMatrix(scanner, firstMatrix);
System.out.println("Reading data to second matrix");
readMatrix(scanner, secondMatrix);
System.out.println("First Matrix");
displayMatrix(firstMatrix);
System.out.println("Second Matrix");
displayMatrix(secondMatrix);
}
}
for(int i = 0; i < n1*n1; i++)
{
for(int j = 0; j < n2*n2; j++)
{
if(fileInput.hasNextInt())
{
if(i < n1){
firstMatrix[i][j] = fileInput.nextInt();
}
else
{
secondMatrix[i][j] = fileInput.nextInt();
}
}
}
}
You have two matrix of size n*n so you can do like this:

Array Index out of bounds exception, when I run this, I am not able to figure out why. I am not able to view the sorted array [duplicate]

This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
import java.util.Scanner;
public class Sort {
public void Countsort(int a[], int b[], int k) throws ArrayIndexOutOfBoundsException {
int[] c = new int[k + 1];
for (int i = 0; i < k; i++) {
c[i] = 0;
}
for (int i = 0; i <= a.length; i++) {
c[a[i]] = c[a[i]] + 1;
}
for (int i = 1; i <= k; i++) {
c[i] = c[i] + c[i - 1];
}
for (int i = a.length; i <= 1; i--) {
b[c[a[i]]] = a[i];
c[a[i]] = c[a[i]] - 1;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
int[] temp = new int[10000];
int i = 0;
while (sc.hasNextInt()) {
num = sc.nextInt();
temp[i] = num;
i++;
if (num == -1) {
break;
}
}
int A[] = new int[i];
// just a check
for (i = 0; i < temp.length; i++) {
System.out.println("temp values:" + temp[i]);
}
// just a check ends
for (int j = 0; j < A.length; j++) {
A[j] = temp[j];
System.out.println("tem copied vals:" + A[j]);
}
// a check for gthat a has temp values..
int[] B = new int[A.length];
new Sort().Countsort(A, B, 100);
for (i = 0; i < B.length; i++) {
System.out.println("Run count #" + i + " : " + B[i]);
}
}
}
First of all your while loop should be
while (sc.hasNextInt()) {
num = sc.nextInt();
if (num == -1) {
break;
}
// so that you can stop -1 to be stored
temp[i] = num;
i++;
}
Next thing is your loop
for (int i = 0; i < a.length; i++) { // always less than length of the array
c[a[i]] = c[a[i]] + 1;
}

Why am I getting a '.class' expected error? Simple Array script

My program is creating an array and allowing the user to input 10 double precision numbers. Then the program will sort them in order from lowest to highest. I have the following but receive .class expected error upon compiling. Any ideas on why this is happening? Note * I have not been able to compile this yet so I don't even know if this will work. *
import java.io.*;
public class ArrayDemo
{
public static void main(String[] args) throws IOException
{
int i = 0;
int j = 0;
int temp = 0;
double[] intValue = new double[10];
String[] numbers = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"};
int len = intValue.length[];
BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
for (i = 0; i < len; ++i)
System.out.println("Enter the " + numbers[i] + " number");
intValue[i] = Double.valueOf(dataIn.readLine());
{
for (j = 0; j < (len - 1) -i; j++)
if (intValue[j] > intValue[j+1])
{
temp = intValue[j];
intValue[j] = intValue[j+1];
intValue[j+1] = temp;
}
for (i = 0; i < 10; i++);
{
System.out.println("Array after sorting in ascending order");
System.out.println();
System.out.println(intValue[i]);
}
}
}
}
Thank you for any input. :)
int temp = 0; should be double temp = 0;
and
int len = intValue.length[]; should be int len = intValue.length;
and
for (i = 0; i < 10; i++); should be for (i = 0; i < 10; i++)
Sample
EDIT
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
int i = 0;
int j = 0;
int k = 0;
double temp = 0;
double[] intValue = new double[10];
String[] numbers = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"};
int len = intValue.length;
BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
for (i = 0; i < len; ++i) {
System.out.println("Enter the " + numbers[i] + " number");
intValue[i] = Double.valueOf(dataIn.readLine());
}
for (j = 0; j < len; j++)
{
for(k = 0; k < len; k++) {
if (intValue[j] > intValue[k])
{
temp = intValue[j];
intValue[j] = intValue[k];
intValue[k] = temp;
}
}
}
System.out.println("Array after sorting in ascending order");
for (i = 0; i < 10; i++)
{
System.out.print(intValue[i] + ", ");
}
}
}
int len = intValue.length[];
You don't need [] after length and you also tried to assign int temp to a value in a double array
temp = intValue[j];
Also using an IDE like Eclipse/NetBeans/IntelliJ would definitely help!
int len = intValue.length[];
should instead be:
int len = intValue.length;
Also, some of your bracketing appears to be incorrect. I believe, for example, that you want the following snippet:
for (i = 0; i < len; ++i)
System.out.println("Enter the " + numbers[i] + " number");
intValue[i] = Double.valueOf(dataIn.readLine());
Changed to:
for (i = 0; i < len; ++i)
{
System.out.println("Enter the " + numbers[i] + " number");
intValue[i] = Double.valueOf(dataIn.readLine());
}
You have a number of other logical errors in your code as well. Let me know, after you work with the code for a while based on the current answers, if you have any specific questions and I will help you further.

Categories

Resources