Java programming double dimensional arrays - java

My aim here is to type a simple code to take in number input from the user and print a simple matrix. The code I typed seems to compile but doesn't work during run time! My code is something like this:
import java.util.Scanner;
class Arr
{
public static void main()
{Scanner in=new Scanner(System.in);
int a[ ][ ]=new int[2][3];
for(int i=0;i<2;i++)
{
for(int y=0;y<2;y++)
{
a[i][y]=in.nextInt();
}
}
for(int i=0;i<2;i++)
{
for(int y=0;y<2;y++)
{
System.out.print(a[i][y]);
}
}
}
}
At the same time could you suggest a solution if I were to transpose the matrix inputted by the user?

You have defined the main method incorrectly. The proper main method signature is
public static void main (String[] args)
That's why the compiler is not compiling your code.

Related

How can I pass these parameters (java)?

I am very new to Java, and I'm having a difficult time figuring out how to take arguments from the command prompt and pass them around in my code. I am able to get them into the main method of my code, but I'd rather have them in the Chessboard class. There is a public static int n that is hard coded, but I would like it to be whatever I send in as arguments. I'll later be taking an initial position for a queen's placement, so I'm hoping the process will be similar; if I get help with this, hopefully I can use the same technique for that.
public class Chessboard {
public static void main(String[] args) {
System.out.println("Hello World");
Chessboard board = new Chessboard(); //creates a Chessboard object
board.start();
}
public static int n = 8;
private static int board[][]; //this is the Chessboard array
private int numQueens; //this is the number of queens on the board
public Chessboard(){
numQueens = 0; //initialized to zero, no queens on board to start yet
board = new int[n][n]; //nxn 2D array of zeros
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
board[j][k] = 0; //redundant, but I need to learn how to
} //initialize. this manually puts zeros into
} //the array
}
...and the code continues from here, but I don't think it's necessary. If it is, I'm happy to upload it.
Thank you for your time.
Here's what I'd do.
public static void main(String[] args) {
try {
int firstArg = Integer.parseInt(args[0]);
Chessboard board = new Chessboard(firstArg);
// Do some stuff with the chessboard here.
}
catch(NumberFormatException e) {
System.out.println("That's not a number");
}
}
This looks at the first command line argument and tries to convert it to an int. If it succeeds, it passes that int to the constructor of Chessboard to make an object for you to use.
This snippet also shows how you can provide code that runs if the first command line argument isn't actually a number.
Notice that the main method is already in your Chessboard class. If you want to leave your n variable as static, you can just do this in the main method.
n = Integer.parseInt(args[0]);
If you make n an instance variable instead of having it be static, then the answer that David Wallace gave will point you in the right direction.
In your Chessboard Class create an
private String[] args;
Then add an setter to Chessboard like:
public void setArgs(String[] args{
this.args = args;
}
Then put something like this in your main:
public static void main(String[] args) {
Chessboard board = new Chessboard();
board.setArgs(args);
board.start();
}

calculate number of occurrences in array in java

I want to calculate the number of occurences of a specific number I decide in my main method. Here is what I have to do :
• A function that fills the array with random numbers.
• A function that calculates the number of occurrences,this function may not do any input or output.
• The main function that asks the user for the number and present the result on the screen.
Here is my code in java :
import java.util.Random;
import java.util.Scanner;
public class Code {
public void calculate(int value) {
Code c = new Code();
int count=0;
for (int n=0; n<array.length; n++) { // the code does not recognize array
if (array[n]==value) { // the code does not recognize array
count++;
}
}
System.out.println(count);
}
public void addToArray() {
int k =0;
int [] array = new int[10];
int min=0;
int max=10;
int diff = max-min;
while (k<10) {
Random r = new Random();
int x = r.nextInt(diff);
array[k]=x;
k=k+1;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("give your number");
Code c = new Code();
Scanner s = new Scanner(System.in);
int value = s.nextInt();
c.addToArray();
c.calculate(value);
}
}
The only thing I need help with is the calculate method ,, eclipse does not recognize array in the calculate method above ..
How to correct the calculate method to make it recognize array ?
thank you
Your array is limited to the scope of the method addToArray(). So, it will not be visible to other methods. You need to make it global. Then it will work.
Instead of declaring array in the method addToArray, declare it in your class, like:
public class Code {
int [] array = new int[10];
...
if using Java 8 you could update your calculate methode like this :
public void calculate(int value) {
System.out.println(Arrays.stream(array)
.filter(i -> i == value)
.count());
}
By adding this imports to your class :
import java.util.Arrays;
And like mentionned HackerDarshi declaring the attribut array as a member of your class

why cant i use System.out.println out side a method and when i try to use the method of my main class in other class it shows identifier not found [duplicate]

This question already has answers here:
Why can't I do assignment outside a method?
(7 answers)
Closed 7 years ago.
why cant i use System.out.println out side a method and when i try to use the method of my main class in other class it shows identifier not found
may be there are better way to do this . but i would like to learn this what is wrong here
package arraytest; //package declared
import java.util.Scanner; // for input
public class Arr { // this is my main class
void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
{ if(min>arr[i])
min=arr[i];
}
System.out.println(min);
}
public static void main(String[] args)
{
Array a=new Array();
a.inputData();
a.display();
a.min();
}
}
class Array
{
int arr[]=new int[5];
Scanner sc= new Scanner(System.in);
// System.out.println(arr.length); will not work why?
void inputData()
{
for(int i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
}
void display()
{
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
void min()
{
Arr a=new Arr();
a.min(int arr[]); // this shows error
}
}
You can't put code there. Your code has to be inside of a method. The 2 lines above that are declarations, and the System.out.println is code.
Code has to go inside a method.'
You could use a static block if your arr was static, but it's not.
Change you min method as below,
void min() {
Arr a = new Arr();
a.min(arr); // this shows error
}
This is how you pass a reference of an array to the method.

Exception in thread main error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
I'm hoping this is just a simple error here, I've looked up numerous other instantces of people getting the same error message but none of their solutions really seem to apply for me. I was just wondering if you guys could help me find the error in my code. I'm not even sure if it's functional because I can't get it to run, so I suppose it could be a logic error.
When I try to run the following cold I am met with fatal exception error occured. Program will exit.
Eclipse also gives me:
java.lang.NoSuchMethodError: main
Exception in thread "main"
Thank you very much for any assistance you can offer!
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JoPuzzle
{
public static Integer main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of soliders");
int soldiers = input.nextInt();
System.out.println("Please enter the how many soldiers are skipped before the next death");
int count = input.nextInt();
List<Integer> soldiersList = new ArrayList<Integer>(soldiers);
for (int i = 1; i <= count; i++) {
soldiersList.add(i);
}
int currentIndex = 0;
while(soldiersList.size() > 1) {
currentIndex = (currentIndex - 1 + count) % soldiersList.size();
soldiersList.remove(currentIndex);
}
return soldiersList.get(0);
} //end main
}//end class
We know that to execute any java Program we should have a main function. because this is a self callable by JVM.
And the signature of the function must be..
public static void main(String[] args){
}
but in your code it's seem like this...
public static Integer main(String[] args){
}
so its consider as a different function , so change your main return type..
The signature for main method is
public static void main(String[] args).
When you run your program the JVM will look for this method to execute. You need to have this method in your code
Your program does not contain the main method, change it to
public static void main(String[] args)
If you want to return an Integer object, then define a custom mehod and call that method inside the main method and handle that returned value.
Java main() function doesn't have a return-statement. This line
public static Integer main(String[] args)
should be
public static void main(String [] args)
Also since it has no return value, you should delete the return statement.
Java's main method should have below signature.
public static void main(String[] args){
..
..
}
Try to run this code and tell if it works.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JoPuzzle
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of soliders");
int soldiers = input.nextInt();
System.out.println("Please enter the how many soldiers are skipped before the next death");
int count = input.nextInt();
List<Integer> soldiersList = new ArrayList<Integer>(soldiers);
for (int i = 1; i <= count; i++) {
soldiersList.add(i);
}
int currentIndex = 0;
while(soldiersList.size() > 1) {
currentIndex = (currentIndex - 1 + count) % soldiersList.size();
soldiersList.remove(currentIndex);
}
// return soldiersList.get(0);
System.out.println(soldiersList.get(0));
} //end main
}//end class

matrix addition java

I wrote this matrix addition program and I dont know why but I keep getting this two errors on lines 61 and 63 and i dont want to handle the exceptions but just throwing would do
error: unreported exception IOException; must be caught or declared
The code of the program is as follows:
import java.io.*;
class Arr
{
int r,c;
int arr[][];
Arr(int r,int c)
{
this.r=r;
this.c=c;
arr=new int[r][c];
}
int[][] getMatrix()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.println("enter element");
arr[i][j]=Integer.parseInt(br.readLine());
}
}
return arr;
}
int[][] findsum(int a[][],int b[][])
{
int temp[][]=new int[r][c];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
temp[i][j]=a[i][j]+b[i][j];
return temp;
}
void putmatrix(int res[][])
{
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.println(res[i][j]+"\t");
}
}
System.out.println();
}
}
class Matrixsum
{
public static void main(String args[])
{
Arr obj1=new Arr(3,3);
Arr obj2=new Arr(3,3);
int x[][],y[][],z[][];
System.out.println("\nEnter matrix 1");
x=obj1.getMatrix();
System.out.println("Enter matrix 2");
y=obj2.getMatrix();
z=obj1.findsum(x,y);
System.out.println("the sum matrix is");
obj2.putmatrix(z);
}
}
Because getMatrix throws IOException which must be caught or declared as thrown by main.
In your case the simplest solution is to declare it on main.
public static void main(String... args) throws IOException
getMatrix() is declared to throw IOException. Calls to getMatrix() in main() can generate IOExceptions, which are required to be caught by the function or rethrown. To solve the problem, you could declare main() to throw IOException.
The design of class Arr is a bit strange. Instead of using two redundant objects obj1 and obj2, you should condense it to one object, say one called arrProcessor. So the calls would look like:
x=arrProcessor.getMatrix();
y=arrProcessor.getMatrix();
z=arrProcessor.findSum(x,y);
arrProcessor.putMatrix(z);
Even better, instead of using arrays, you should wrap the arrays in objects, say in a class called Matrix:
public class Matrix{
int[][] values;
int numRows, numCols;
protected Matrix(){/*...*/}
public static Matrix getMatrix(int nRows, int nCols){/*...*/}
public static Matrix addMatrices(Matrix a, Matrix b) throws Exception {/*...*/}
public void print(){/*...*/}
public void plus(Matrix another) throws Exception {/*...*/}
}
So now the code would look like:
Matrix x,y,z;
x=Matrix.getMatrix(3,3);
y=Matrix.getMatrix(3,3);
z=x.plus(y);
z.print();
hey i would suggest you this one.
http://commons.apache.org/math/userguide/linear.html
If you tired to write your own code with matrix, just download library I developed. It can add, multiply, invert, transpond, calculate determinant and solve linear systems.
please check: Linear Math Library
This is open source you can download the source code too and look how in works.

Categories

Resources