Noob to programming... I need to create a function that receives a 2d array and requests user input to fill both the rows and the columns. The error that shows me is "empty statement" / "not a statement" on the last line.
public static void fillMatrix(int [][] pmatrix) throws IOException {
int [][] matrix = new int [pmatrix.length][pmatrix.length];
int i, k; //loop variables
int rows, columns;
for(i = 0; i < pmatrix.length; i++){
print.println("set the value of the row " + (i + 1));
rows = Integer.parseInt(read.readLine());
}
for(k = 0; k < pmatrix.length; k++){
print.println("set the value of the column " + (k + 1));
colums = Integer.parseInt(read.readLine());
}
matrix = {{rows}, {columns}};
}
First, what you do here is reassigning the variables rows and columns in each iteration. So at the end, you will have one single value per row in your matrix.
Second, you're reassigning the local variable matrix to be a Matrix, that has two rows and one column. And since it doesn't have anything to do with the parameter pmatrix, nothing will happen to it after the method returns.
I assume you want to call that method on an empty 2D-Array and fill it with values from the console. To iterate through a 2D-Array, you will need a nested for-loop and access each index in your matrix individually:
public static void fillMatrix(int [][] pmatrix) throws IOException {
for(i = 0; i < pmatrix.length; i++){
for(int j = 0; j < pmatrix[i].length; i++ {
print.println("set the value of row " + (i + 1) + " in column " + (j + 1));
pmatrix[i][j] = Integer.parseInt(read.readLine());
}
}
}
It is easier to understand in the full context.
The following code has a main method that creates a matrix of size 3x3, you can change this if you like.
Next, it calls the fillMatrix method and then the printMatrix method.
fillMatrix goes through each row and for each row, it goes through each column. For an entry in the matrix, it reads an integer using Scanner instead of BufferedReader because it is easier to use.
printMatrix runs through all the entries and prints them as a table.
Running the program and giving 1 2 3 4 5 6 7 8 9 prints
1 2 3
4 5 6
7 8 9
The program
import java.io.IOException;
import java.util.Scanner;
public class Helper {
public static void main(final String[] args) throws IOException {
final int[][] matrix = new int[3][3];
fillMatrix(matrix);
printMatrix(matrix);
}
public static void fillMatrix(final int[][] matrix) throws IOException {
final Scanner scanner = new Scanner(System.in);
for (int i = 0; i < matrix.length; i++) {
final int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
final int userInput = scanner.nextInt();
row[j] = userInput;
}
}
}
private static void printMatrix(final int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
final int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
System.out.print(row[j] + " ");
}
System.out.println();
}
}
}
Related
Complete question is: Create a program that uses a two dimensional array that can store integer values inside. (Just create an array with your own defined rows and columns). Make a method called Square, which gets each of the value inside the array and squares it. Make another method called ShowNumbers which shows the squared numbers.
What I attempted thou it has errors:
public class SquareMatrix {
public static void main(String[] args) {
int sqr[][]= {{1,3,5},{2,4,6}};
System.out.println("Your Original Matrix: ");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
System.out.print(sqr[i][j] + " ");
}
System.out.println();
}
Square();
ShowNumbers();
}
static void Square(){
for(int i = 0; i <= 1; i++) {
for(int j = 0; j <= 2; j++) {
sqr[i][j] = sqr[i][j] * sqr[i][j];
}
}
}
static void ShowNumbers(){
System.out.println("Matrix after changes: ");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
System.out.print(sqr[i][j] + " ");
}
System.out.println();
}
}
}
Also how would I write it if I wanted an input from the user for the col and row for a specific range of 0 to 10, I made an alternative version with many errors below. Below code is not as important as the one above
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
try{
System.out.print("Enter Number of Row for Array (max 10) : ");
row = scan.nextInt();
System.out.print("Enter Number of Column for Array (max 10) : ");
col = scan.nextInt();
if(0>=row && row<=10 || 0>=col && col<=10 ){
}
}
catch (Exception e){
System.out.println("(!) Wrong input...\n");
}
System.out.print("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++){
for(j=0; j<col; j++){
arr[i][j] = scan.nextInt();
}
}
}
static void square(){
arr[row][col] = arr[row][col] * arr[row][col];
}
static void ShowNumbers(){
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}}}
PS I am new to java and would appreciate a response with the whole code pasted not just a section of the code so I don't get lost or with the number of the line the error is from.
thanks for any help
Since you are starting from scratch, it would be good to go over the basics of the language again. Take a look at oracle classvars For your upper problem you need to understand the difference between local and instance variables and the difference between static and non static variables respectively. To solve your issue just move the declaration of your array out of the main method and add a static modifier:
public class SquareMatrix {
static int sqr[][] = {{1, 3, 5}, {2, 4, 6}};
public static void main(String[] args) {
//rest of your code
}
I need to delete row and column where max value in 2d array exist,please suggest how to do it.
Here is an array in which specific row and column must be delted. I suppose here can be used aaraycopy
import java.util.Scanner;
public class Test{
public static void main (String[] args){
int maxValue=0;
int[][] multiplyTab = new int[5][10];
int row = 0;
int column=0;
for (int i = 0; i < multiplyTab.length; i++) {
for (int j = 0; j <multiplyTab[i].length ; j++) {
multiplyTab[i][j] =((i+1)*(j+1));
System.out.print(multiplyTab[i][j] + "\t");
}
System.out.println();
}
for (int i = 0; i < multiplyTab.length; i++) {
for (int j = 0; j < multiplyTab[i].length; j++) {
if (multiplyTab[i][j] > maxValue) {
maxValue = multiplyTab[i][j];
row=i;
column=j;
}
}
}
}
}
To delete row i from a 2D array like yours, first create a new 2D array that is one element shorter (4 instead of 5 in your example). Copy rows 0 through i - 1 and rows i + 1 through originalTable.length - 1 into the new array.
Edit: when maxValue is in the last row (as here if I am not mistaken) and hence the last row is to be deleted, it is of course a bit easier since there are no rows i + 1 through originalTable.length - 1 to copy.
To delete column j do similarly to every inner array of the table.
Hey guys so this is my homework question: Write a method that displays an n by n matrix in a dialog box using the following header:
public static void printMatrix(int n)
Each element in the matrix is 0 or 1, which is generated randomly.
A 3 by 3 matrix may look like this:
0 1 0
0 0 0
1 1 1
So far, I could easily print out my problem in a scanner, however I'm not sure how to do it in a dialog box.
At the moment I'm getting the error:
error: 'void' type not allowed here JOptionPane.showMessageDialog(null, printMatrix(n));
1 error
I know that it's a void, and can't be returned however, my assignment requires the method to be void. My real question is how would I print it in the method then? I've been working on this problem for 4 hours and it's really frustrating me.
import java.util.*;
import java.lang.*;
import java.io.*;
import javax.swing.JOptionPane;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
// Main method
public static void main(String[] args)
{
// Prompt user to enter numbers
String stringInteger = JOptionPane.showInputDialog(null, "Enter a integer n to determine the size of matrix: ", "Size of Matrix Input", JOptionPane.INFORMATION_MESSAGE);
// Convert string to integer
int n = Integer.parseInt(stringInteger);
JOptionPane.showMessageDialog(null, printMatrix(n));
}
// Generate and display random 0's and 1's accordingly
public static void printMatrix(int n)
{
// Row depending on n times
for (int row = 0; row < n; row++)
{
// Column depending on n times
for (int col = 0; col < n; col++)
{
String randomN = ((int)(Math.random() * 2)+ " ");
}
}
}
}
I think you are being asked to print. Also, I would prefer Random.nextBoolean() for generating the character. Loop and call System.out.print. Something like,
public static void printMatrix(int n) {
Random rand = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(rand.nextBoolean() ? "1 " : "0 ");
}
System.out.println();
}
}
public static void main(String[] args) {
printMatrix(3);
}
If you really want to use a JOptionPane you might use a StringBuilder to construct the matrix and then display it. Something like,
public static void printMatrix(int n) {
Random rand = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sb.append(rand.nextBoolean() ? "1 " : "0 ");
}
sb.append(System.lineSeparator());
}
JOptionPane.showMessageDialog(null, sb.toString());
}
But a void method doesn't return anything, so you can't print the result of a void method in the caller.
A slight modification done to your method I am providing screenshot of output.
private static Object printMatrix(int n) {
// Column depending on n times
String randomN[][] = new String[n][n];
for(int row = 0 ;row<n;row++)
{
for (int col = 0; col < n; col++)
{
randomN[row][col] = ((int)(Math.random() * 2)+ " ");
}
}
String s = Arrays.deepToString(randomN).replace("], ", "\n").replaceAll(",|\\[|\\]", "");
return s;
}
Hope you found my code helpful cheers happy coding.
This code will do everything inside your printMatrix();
class DialogPrint
{
public static void main(String[] args)
{
// Prompt user to enter numbers
String stringInteger = JOptionPane.showInputDialog(null, "Enter a integer n to determine the size of matrix: ", "Size of Matrix Input", JOptionPane.INFORMATION_MESSAGE);
// Convert string to integer
int n = Integer.parseInt(stringInteger);
printMatrix(n);
}
// Generate and display random 0's and 1's accordingly
public static void printMatrix(int n)
{
// Row depending on n times
String sb="";
for (int row = 0; row < n; row++)
{
// Column depending on n times
for (int col = 0; col < n; col++)
{
String randomN = ((int)(Math.random() * 2)+ " ");
sb+=randomN;
}
sb+="\n";
}
System.out.print(sb);
JOptionPane.showMessageDialog(null, sb);
}
}
I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.
Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.