我试图将一个方法中的三个整数传递给Java中同一个类中的另一个方法。
我当前的代码看起来像这样(但简化了):
import java.util.Scanner;
public class One()
{
int var1 = 33;
int var2 = 34; //these three have to sum to 100
int var3 = 33;
//this is in a while loop in case the three numbers != 100
public int two()
{
Scanner in = new Scanner(System.in);
//let user change var1, var2, var3 if they want
if (var1 + var2 + var3 == 100)
{
//I would guess the code for passing the variables is here
break;
}
//else statement
}
public int three()
{
//transfer var1, var2, var3 here and do stuff with it
}
}
我看了这个,显然我必须创建一个对象或一个数组来将它们传递给另一个方法(?)。但是,我觉得有一种更简单的方法可以做到这一点,因为我班上只有两种方法。
答案 0 :(得分:0)
import java.util.Scanner;
public class One()
{
int var1 = 33
int var2 = 34 //these three have to equal 100
int var3 = 33
//this is in a while loop incase the three numbers != 100
public int two()
{
Scanner in = new Scanner(System.in);
//let user change var1, var2, var3 if they want
if (var1 + var2 + var3 == 100)
{
three(var1,var2,var3); //call the method, supplying the 3 parameters
}
//else statement
}
public int three(int var1, int var2, int var3) //declare your method parameters
{
//transfer var1, var2, var3 here and do stuff with it
return 0;//return an int
}
答案 1 :(得分:0)
您可以按照以下方式执行此操作:
import java.util.Scanner;
public class One {
int var1 = 33;
int var2 = 34; //these three have to equal 100
int var3 = 33;
Scanner sc = new Scanner(System.in);
public void two() {
if (var1 + var2 + var3 == 100) {
three(var1, var2, var3);
}
//else statement
}
public void three(int a, int b, int c) {
//transfer var1, var2, var3 here and do stuff with it
System.out.println(a);
}
public static void main(String args[]){
new One().two();
}
}
此外,
与方法
break语句只允许在loops / switch中使用,
答案 2 :(得分:0)
几点: