1

这是我的程序,它对名为“initialMarks”的数组中的数字进行一些计算。但是我想使用扫描仪从另一个类中填充 initialMarks 数组。你能帮我弄清楚该怎么做吗?是否可以在第三类中输出结果数组“结果”?

public class testingN
{
    public static void main(String[] args) 
    {
           int [] initialMarks = new int [4];
           int [] result = new int [6];
           result[0] = computedMarks(initialMarks[0], initialMarks[1])[0];
           result[1] = computedMarks(initialMarks[2], initialMarks[3])[1];

            for(int i=0; i< result.length; i++)
                  System.out.println(result[i]);
    }

    public static int [] computedMarks(int mark1, int mark2) 
    {   
        int [] i= new int [6];
            for (int j = 0; j < i.length; j++)
        {                   
              if ((mark1 < 35 && mark2 > 35) || (mark1 > 35 && mark2 < 35))
              {
                i[j] = 35;
              }
              else
              {
                i[j] = (mark1 * mark2);
              }
        }
        return i;
    }
}
4

2 回答 2

0
public class testingN
{
    static int [] result = new int [6];
    static int [] initialMarks = new int [4];

    public static void main(String[] args) 
    {

声明result为类成员(全局变量)并存在static应该有助于您的事业

示例:从另一个类中使用

public class AnotherClass {

    public static void main(String[] args) {
        // example
        testingN.result[0] = 4;

        System.out.println(testingN.result[0]);
    }
}

编辑:运行下面的代码Here。你会看到它工作得很好。

class testingN
{
    static int [] result = new int [6];
    static int [] initialMarks = new int [4];
}

public class AnotherClass {

    public static void main(String[] args) {
        // example
        testingN.result[0] = 4;

        System.out.println(testingN.result[0]);
    }
}
于 2013-10-30T19:03:09.433 回答
0

您的其他类可以有一个返回流的方法,您可以将其提供给 Scanner 的构造函数。

在您的其他类的 String getInitialMarks() 方法中:

// Generate a string with all the "marks" as "stringWithMarks", separated by "\n" characters
InputStream is = new ByteArrayInputStream( stringWithMarks.getBytes( "UTF-8" ) );
return is;

然后在你的第一堂课 otherClass:

Scanner scanner = new Scanner(otherClass.getInitialMarks());

并继续阅读标记,就好像它是用户输入一样。

于 2013-10-30T19:06:10.183 回答