Reputation: 11184
try to create new method, but during running it's not working code this placed on
class Matrix {
public static void main (String args[]) throws IOException {
...
System.out.println("Enter q-ty of matrix elements i= ");
int gormatelement = 0;
getchartoint (gormatelement);
...
}
...
}
and after method
public static void getchartoint (int a) throws IOException{
BufferedReader bReader = new BufferedReader (new InputStreamReader(System.in));
String k = bReader.readLine();
a = Integer.parseInt(k);
}
this code must get char from console and convert it to int - will be used as q-ty of elements in matrix
Upvotes: 0
Views: 140
Reputation: 207
You are assigning the result of of parseInt() to a, which is a local copy of "gormatelement" and which is deleted once the function ends. Java uses "call-by-value" for primitive data types.
You could also take a look at the Scanner Class:
public static int getIntFromCommandLine() {
Scanner scan = new Scanner(System.in);
return scan.nextInt();
}
Upvotes: 0
Reputation: 12985
When you change the value of a simple parameter variable (like a) inside a method, it does not change the variable that you gave when you called the method (like gormatelement).
The easiest way to do this is to have the method return the integer value and the calling code to store it.
int gormatelement = getchartoint ();
and
public static int getchartoint () throws IOException{
int a;
... same code ...
return a;
}
Expanded
If you want to go look up more about this concept of passing variables, you can Google the terms "call by value" and "call by reference".
Java uses a "call by value" but it is easy to get confused when objects with contained instance variables are passed to a method because the contained field values can be changed and the change seems to propagate to the object you called the method with.
What's happening is that the value of an Object is really a reference to the obect's contents, so to speak. You have to think about it a while to see what I mean.
Upvotes: 2
Reputation: 6121
public class x
{
public static void main(String[] args)
{
System.out.println("Enter q-ty of matrix elements i= ");
int gormatelement = 0;
getchartoint (gormatelement);
}
public static void getchartoint (int a) throws IOException{
BufferedReader bReader = new BufferedReader (new
InputStreamReader(System.in));
String k = bReader.readLine();
a = Integer.parseInt(k);
}
}
Since you are a beginner, At least this is required for your program to compile.
Upvotes: 1