how to print 2d integer array using scanner in java - java

System.out.println("Enter the No. of rows to dispaly in 2d");
Scanner n = new Scanner(System.in);
double r = n.nextInt();
System.out.println("Enter the No. of cols to dispaly in 2d");
Scanner v = new Scanner(System.in);
double q= v.nextInt();
System.out.println("Enter the data");
Scanner sc = new Scanner(System.in);
int d = sc.nextInt();
int x[][]={};
int z,y=0;
for ( y=0; y<r.length; y++)
{
for (z=0; z<q.length; z++)
{
x[y][z] = sc.nextInt();
}
}
for ( int m=0; m<x.length; m++)
{ for(int p=0; p<x.length; p++)
{
System.out.println("x[" +m + "][" +p +"]=" +x[m][p]);
}
}

for(int p=0; p<x.length; p++)
is not correct, p need to go from 0 to x[m].length
You need something like this:
for(int m = 0; m < x.length; m++)
{
for(int p = 0; p < x[m].length; p++)
{
System.out.println("x[" + m + "][" + p +"]=" +x[m][p]);
}
}
a 2d array is an array of arrays, so second for loop sees 1d arrays which also have the length property.

Problems with your code:
System.out.println("Enter the No. of rows to dispaly in 2d");
Scanner n = new Scanner(System.in);
double r = n.nextInt();//why use double? use int r=n.nextInt();
System.out.println("Enter the No. of cols to dispaly in 2d");
Scanner v = new Scanner(System.in);//why create another Scanner object, use the old one.
double q= v.nextInt();//int here again
System.out.println("Enter the data");
Scanner sc = new Scanner(System.in);//not another scanner
int d = sc.nextInt();
int x[][]={};
int z,y=0;
for ( y=0; y<r.length; y++)//what's with the length of a double?
{
for (z=0; z<q.length; z++)
{
x[y][z] = sc.nextInt();
}
}
for ( int m=0; m<x.length; m++)
{ for(int p=0; p<x.length; p++)//need to use x[m].length
{
System.out.println("x[" +m + "][" +p +"]=" +x[m][p]);
}
}

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

Math Equation Pattern

I am creating a pattern that, when user enters the number of rows, prints a triangle with a specific number pattern. I am having a hard time coming up with a mathematical equation that will output this pattern:
I have already written a code that works but not with the pattern that I am wanting to create. Can someone help me?
Here's my code so far:
import java.util.Scanner;
public class trianglePattern {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
for(int i =0;i<rows;i++) {
System.out.format("%"+4*(rows-i+1)+"s","");
for(int j=i+1; j>1; j--)
System.out.format("%4d", j);
for(int j=1; j<=i+1; j++)
System.out.format("%4d", j);
System.out.println();
}
}
}
Switched the loops, added a power function and fiddled a little with the loop indexes:
import java.util.Scanner;
public class trianglePattern {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
for(int i = 0; i < rows; i++) {
System.out.format("%"+4*(rows-i+1)+"s","");
for(int j = 0; j <= i; j++)
System.out.format("%4d", (int) Math.pow(2,j));
for(int j = i - 1; j >= 0; j--)
System.out.format("%4d", (int) Math.pow(2,j));
System.out.println();
}
}
}
Nice problem...
Scanner input = new Scanner(System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<rows; i++) {
list.add(i);
}
for(int i=rows-2; i>-1; i--) {
list.add(i);
}
// I print this here just for your help(delete it afterwards)
for (Integer integer : list) {
System.out.print(((int) Math.pow(2, integer)) + " ");
}
System.out.println("\n");
for(int i=rows; i>=1; i--) {
for (Integer integer : list) {
int number = ((int) Math.pow(2, integer-i+1));
if(number>=1) {
System.out.format("%d\t", ((int) Math.pow(2, integer-i+1)));
} else {
System.out.print(" ");
}
}
System.out.println("\n");
}
(Tip): in the Arraylist list i save all the exponents i need to calculate the last row of the problem.
Try this. The spacing is based on several factors.
The sum of the field widths. Each field width is kept is a list. It is used to reduce the leading space based on the row being printed.
That each column field width is sized for the maximum value in that column. The width for a given column is also maintained in a list. Since the widths are symmetric about the central column, left side formats are also used to print right side values.
Scanner input = new Scanner(System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
List<Integer> fws = new ArrayList<>();
List<String> fmts = new ArrayList<>();
Function<Integer, Integer> fw = r -> (int) (Math
.log10(1 << r)) + 2;
int sumWidths = 0;
for (int r = 0; r < rows; r++ ) {
int f = fw.apply(r);
fws.add(f);
sumWidths += f;
fmts.add("%" + f + "d");
}
rows--;
String pad = " ".repeat(sumWidths);
for (int r = rows; r >= 0; r--) {
System.out.print(pad);
int v = 1;
for (int c = r; c < rows; c++) {
System.out.printf(fmts.get(c), v);
v <<= 1;
}
System.out.printf(fmts.get(rows), v);
for (int c = rows-1; c >= r; c--) {
v >>= 1;
System.out.printf(fmts.get(c), v);
}
System.out.println();
pad = pad.substring(r > 0 ? fws.get(r-1) : pad.length());
}
}

How to deal with multiple lines input with Scanner

Input i have to deal with:
2
2 3
3 3
My code:
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[][] array = new int[size][2];
Scanner scanner2 = new Scanner(System.in);
for (int i=0; i<size; i++) {
for (int j=0; j<2; j++) {
array[i][j] = scanner2.nextInt();
}
}
2 is number of pairs that input contains. I want to put those pairs in 2D array but I need to get 2 first to declare size of an array. Above code works well in NetBeans where I give input like:
number
enter
pair
enter
...
But all numbers come together in a format I posted above.
Any help?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter an integer");
int size = scanner.nextInt();
int[][] array = new int[size][2];
for (int i = 0; i < size; i++) {
String myInt = scanner.next();
String[] myInts = myInt.split(" ");
for (int j = 0; j < 2; j++) {
array[i][j] = Integer.parseInt(myInts[j]);
}
}
// print contents
for (int i = 0; i < size; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("[" + i + "]" + "[" + j + "] = " +array[i][j]);
}
}
}

How to calculate the average of each row and column in array

So yesterday I asked for help, and a lot of people helped me out with my question, I really appreciated that guys. However, I run into a second problem of my homework, and I have been trying to solve it from this morning, and now it's like almost 2AM in the morning, and I'm not gonna sleep until I solve this problem. I'm not going to lie, so this is my homework to test the basic knowledge of mine. I know I make major mistakes somewhere, so please help me to point them out, so I can fix them. Thank you
The output should be:
1, 2, 3, ave=2
4, 5, 6, ave=5
aver=2.5, 3.5, 4.5
This is my current code:
import java.util.Scanner;
public class Ex {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
System.out.print(array[i][j] + " , ");
}
System.out.println("\n");
}
}
double averageRow(int[][] array) {
int rowTotal = 0;
double average = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
rowTotal += array[rows][columns];
}
average = rowTotal / array[rows].length;
System.out.println(average);
rowTotal = 0;
}
return rowTotal;
}
double averageColumn(int[][] array) {
int columnTotal = 0;
double average = 0;
for (int columns = 0; columns < array.length; columns++) {
for (int rows = 0; rows < array[columns].length; rows++) {
columnTotal += array[rows][columns];
}
average = columnTotal / array[columns].length;
System.out.println(average);
columnTotal = 0;
}
return columnTotal;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows");
int r = sc.nextInt();
System.out.println("Enter number of columns");
int c = sc.nextInt();
System.out.println("Enter values");
int[][] matrix = new int[r][c];
for (int i = 0; i < r; i++)
{
float rowSum = 0f;
for (int j = 0; j < c; j++)
{
matrix[i][j] = sc.nextInt();
rowSum += matrix[i][j];
}
System.out.println("Average of row " + i + " " + rowSum / c);
}
for (int i = 0; i < c; i++)
{
float columnSum = 0f;
for (int j = 0; j < r; j++)
{
columnSum += matrix[j][i];
}
System.out.println("Average of column " + i + " " + columnSum / r);
}
sc.close();
}
You can find the each row sum while reading the data. For column average run loop again. Hope you will sleep :)
You can print without calling other function.
import java.util.Scanner;
public class test8 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
int rowSum = 0;
int colSumArr[] = new int[columns];
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
rowSum = rowSum + array[i][j];
colSumArr[j] = colSumArr[j] + array[i][j];
System.out.print(array[i][j] + " , ");
}
System.out.println( " ave=" + (double)rowSum/columns);
rowSum = 0;
}
System.out.printf("aver=");
for(int i=0;i<columns;i++){
if(i!=columns -1)
System.out.print((double)colSumArr[i]/rows + ", ");
else
System.out.print((double)colSumArr[i]/rows);
}
}
}

Lagrange interpolation in JAVA

I have done a search around, but there isnt any code available in java hence I have write my own and I have encountered some issue. I actually got this code from a c++ source and trying hard to convert it into a workable java program.
http://ganeshtiwaridotcomdotnp.blogspot.sg/2009/12/c-c-code-lagranges-interpolation.html
public static void main(String[] args) {
int n;
int i, j;
int a;
int x[] = null;
int f[] = null;
int sum = 0;
int mult;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of point: ");
n = input.nextInt();
System.out.println("Enter value x for calculation: ");
a = input.nextInt();
for (i = 0; i < n; i++) {
System.out.println("Enter all values of x and corresponding functional vale: ");
x = input.nextInt();
f = input.nextInt();
}
for (i = 0; i <= n - 1; i++) {
mult = 1;
for (j = 0; j <= n - 1; j++) {
if (j != i) {
mult *= (a - x[j]) / (x[i] - x[j]);
}
sum += mult * f[i];
}
}
System.out.println("The estimated value of f(x)= " + sum);
}
For Lagrange Interpolation Formula -
You should use double data type Array
Your should make Arrays with specific number of items
Look at the program below, you will understand.
double product, sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Number of Terms: ");
int n = sc.nextInt();
double[] x = new double[n];
double[] y = new double[n];
System.out.println("Enter all the x, y terms: ");
for (int i = 0; i < n; i++) {
x[i] = sc.nextDouble();
y[i] = sc.nextDouble();
}
System.out.println("x = {" + Arrays.toString(x) + "}");
System.out.println("x = {" + Arrays.toString(y) + "}");
System.out.print("Enter a point to Find it's value: ");
int xPoint = sc.nextInt();
// End of inputs
product = 1;
// Peforming Arithmatic Operation
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j != i) {
product *= (xPoint - x[j]) / (x[i] - x[j]);
}
}
sum += product * y[i];
product = 1; // Must set to 1
}
System.out.println("The value at point " + xPoint + " is : " + sum);
// End of the Program
}
}
int x[] = null;
int f[] = null;
...
for (i = 0; i < n; i++) {
....
x = input.nextInt();
f = input.nextInt();
}
Looks clear enough. Simply create array instance for x and f:
x = new int[n];
f = new int[n];
Somewhere after:
n = input.nextInt();
Before above for loop, and modify the for body:
...
x[i] = input.nextInt();
f[i] = input.nextInt();
public static void main(String[] args) {
System.out.println("Langrages");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no of terms: ");
int n = sc.nextInt();
float[] ax = new float[n];
System.out.println("Enter values of x");
for(int i=0 ;i<n;i++) {
ax[i] = sc.nextFloat();
}
float[] ay = new float[n];
System.out.println("Enter values of y");
for(int i=0 ;i<n;i++) {
ay[i] = sc.nextFloat();
}
System.out.println("Enter the value of x\n at which you find y");
int x = sc.nextInt();
float num,den;
float term =0;
for(int i=0;i<n;i++) {
num=1;
den=1;
for(int j=0;j<n;j++) {
if(j!=i) {
num=num*(x-ax[j]);
den = den*(ax[i]-ax[j]);
}
}
term += (num/den)*ay[i];
}
System.out.println(term);
sc.close();
}

Categories

Resources