-1

我是 Java 新手,我试图弄清楚如何使用用户输入的值中的方法。我使用过 Java 扫描器并了解它是如何工作的,但我无法弄清楚如何创建一个使用用户输入的值的方法。

我想创建一些非常简单的东西,以便我可以理解,例如用户输入一个数字,然后用一个方法将这个数字乘以 10。抱歉,如果我遗漏了一些明显的东西,但我已经尝试了几个小时但我不能解决它。

这就是我下面的内容,但是当我尝试在下面添加一个方法时,我得到了不同类型的错误。

import java.util.Scanner;

public class Main {


    public static void main(String[] args) {
        Scanner number = new Scanner(System.in);
        System.out.print("Enter number: ");
        String num = number.nextLine();

4

2 回答 2

1

将用户输入分配给变量后,您可以像使用任何其他变量一样使用它并将其传递给方法。

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    // read user input and assign to the 'num' variable
    int num = in.nextInt();
    // call the method we made and pass the num into it
    myMethod(num);
  }
  // here we define our method and give it one parameter, num
  public static void myMethod(int num) {
    // multiply num variable by 10 and print it
    System.out.println(num*10);
  }
}
于 2020-01-29T21:11:05.703 回答
0

我建议做下一个

import java.util.Scanner;

public class Main {


    public static void main(String[] args) {
        Scanner number = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = number.nextInt()*10;
于 2020-01-29T21:12:41.940 回答