So I just learnt today how to make a secondary class take into account a variable from the main class.
But how do I do the reverse that is a variable with a value in the secondary class have that same value in the main class?
here the code:
package maiN;
public class nintodec {
public static void convertToDec(String number) {
number = new StringBuffer(number).reverse().toString();
int numero = 0;
int mult = 1;
for (int i = 0; i < number.length(); i++) {
int digit = number.charAt(i);
digit = Character.getNumericValue(digit);
numero = numero + (mult * digit);
mult = mult * 9;
}
}
}
as you can see numero is calculated in the secondary class and i want the value returned to this main class:
package maiN;
import java.util.Scanner;
public class director {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("enter a base nine number");
String number = keyboard.next();
nintodec.convertToDec(number);
System.out.println(numero); // here numero is not recognized for is from
// the other class
}
}
答案 0 :(得分:1)
you want to make convertToDec()
return an int
, so change the void
you have there to int
. Then you will want to add return numero;
to the end of your convertToDec
method.
This will make it so that int will get passed back and you can use it later.
then in main you want to do
//other code..
String number=keyboard.next();
int numero = nintodec.convertToDec(number);
System.out.println(numero)
Also, please try reading & learning about some of Java's standards in terms of naming and the like, it will make your code much easier to maintain and read in the future.
答案 1 :(得分:1)
Your issue is about variable scope
,and you can rectify that with following.
You have two options:
Print out the value inside the convertToDec
if you are done with your calculation, as a result, numero
variable no need to be visible there in order to be printed.
Instead of return void
, you should return int
so you can use it for further calculation inside director
class
your function signature change from
public static void convertToDec(String number){
to
public static int convertToDec(String number){
Note: do not forget to use return numero
in your function.
When you return a type int
, the value of numero
variable can be visible to your secondary class so you expand its scope