【问题标题】:Sending integers to a method向方法发送整数
【发布时间】:2016-03-23 18:41:25
【问题描述】:

所以当我编译和运行应用程序时,我得到整数的提示,然后什么都没有。我是否没有正确地将整数发送到方法 multiplynumbers():?

import java.util.Scanner;

public class MultiplyNVRM2
{
  private static int one=0;

  private static int two=0;

  private static int product =one * two;



  public static void main(String [] args)
  {
    Scanner input = new Scanner(System.in);

    System.out.printf("%nPlease enter an integer: ");

       one = input.nextInt();

    System.out.printf("%nPlease enter another integer: ");

       two = input.nextInt();

       input.nextLine();

        multiplyNumbers();


  }//end main()

  public static  int mulitplyNumbers()
  {

      product =  one *  two;

   System.out.printf("%n%d * %d = %d", int one, int two, product);


  }//end multiplyingNumbers
}

【问题讨论】:

  • 这个System.out.printf("%n%d * %d = %d", int one, int two, product); 不是合法代码。
  • 另外,您没有向函数“发送”任何整数。您只是调用一个使用变量一和二的值的函数。
  • 我建议你 a) 编译代码,b) 用你的代码格式化程序整理代码,c) 我建议你将值作为参数传递,而不是静态字段。
  • 任何标准的 IDE 像 Eclipse 都会立即给你写 System.out.printf(); 的错误;

标签: java methods parameters integer


【解决方案1】:

这样做:

public static void mulitplyNumbers(int one, int two) {
    int product = one * two;
    System.out.printf("%n%d * %d = %d", one, two, product);
}

请记住:

  • 如果您的代码没有返回任何内容,请使用关键字void 而不是int。请注意,您将结果打印出来,不要再使用它了。
  • System.out.printf 和任何其他方法中的参数在调用该方法时不需要初始化它们的类型。
  • 使用整数作为参数。你可以调用main中的方法:

    multipleNumbers(one, two);
    

【讨论】:

  • 很高兴它有帮助。请在此处接受对您最有帮助的最佳答案。
【解决方案2】:

此行无效:

System.out.printf("%n%d * %d = %d", int one, int two, product);

你不能在方法printf的参数中使用int这个词,因为你没有声明任何方法......你正在调用它......

尝试一下

 System.out.printf("%n%d * %d = %d", one, two, product);

【讨论】:

    【解决方案3】:
    System.out.printf("%n%d * %d = %d",one,two, product);
    

    【讨论】:

      猜你喜欢
      • 2013-03-18
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-27
      • 2016-01-25
      相关资源
      最近更新 更多