Java 查找从键盘输入的一组数据的最小值

Java 查找从键盘输入的一组数据的最小值,java,methods,pseudocode,Java,Methods,Pseudocode,在我的教科书中,我有一个用伪代码编写的算法,然后应该用Java方法实现。事情是这样的: public class MyAlgorithm { public static void main(String[] args) { // code here } } 读敏; 虽然不是我做的 读x 如果x

在我的教科书中,我有一个用伪代码编写的算法,然后应该用Java方法实现。事情是这样的:

public class MyAlgorithm {
public static void main(String[] args) {
// code here
}
}
读敏; 虽然不是我做的 读x 如果x
import java.util.Scanner;

public class MyAlgorithm  {

   public static void main(String[] args) {
      MyAlgorithm  m = new MyAlgorithm ();
      m.min();
   }

   int min(){
      //Your min code goes here
      return min_value;
    // min_value is the same as your min variable. It has another name to
    // prevent name collisions
   }
}
如果允许您使用静态方法,我认为您不能使用以下替代方法:

static int min(){
    //Your min code goes here
    return min_value;
    // min_value is the same as your min variable. It has another name to
    // prevent name collisions
}

public static void main(String[] args) {
   int result = MyAlgorithm.min();
}

似乎您将min方法放在main中,这是从其他方法中定义方法,这些方法将无法正常工作并且无法编译。main方法是您希望在启动程序后立即运行的命令,类中的任何其他函数都应在其外部声明,如果您希望它们在main中运行,则执行方法调用

它应该是这样的:

import java.util.Scanner;

public class MyAlgorithm {

    int min() {
    //(min code)
    }

    public static void main(String[] args) {
    // code here
    //corrected according to Uli's comment
        MyAlgorithm m = new MyAlgorithm();
        int result = m.min();
    }
}

我建议阅读java程序的结构。这里有一篇关于

的文章,这意味着你必须学习Java!显示所有代码。听起来像,但不清楚您是否在main方法中插入了import和min方法。这就可以解释问题了。你是说你把第一段代码放在main方法里面了吗?您是否试图在main中定义函数?我不确定你的实际代码是什么样子的。如果你想定义min,你需要在main之外做它,然后从main内部调用它。老实说,我不知道我在做什么。我是否正确理解min部分应该进入课堂?还有循环?但是当我这么做的时候,我也犯了一大堆错误。我应该把它放在哪里呢?@cupoftae我已经添加了示例代码,我明白了,你可以参考。我试过这两种结构,它们都起作用了。最后一个可能很愚蠢的问题:我返回1分钟或1分钟有关系吗?@cupoftae是的,有关系。您必须返回min。如果您返回1,这只是一个占位符,您将始终得到1作为min值,这绝对不是您想要的。我将在代码中更改它。这将不起作用,因为主方法是静态的。您首先需要创建MyAlgorithm的对象。@UliSotschok您在我发布之前更新了您的答案,现在这个答案基本上是在重复您拥有的内容,我可能会删除它。您将min函数放在main之外的想法是对的。但是代码中的问题是,如何调用min方法。当你将它粘贴到你的IDE时,这会引起一个错误。我花了太多时间使用C,所以这个错误从我身边溜走了。哈哈。
static int min(){
    //Your min code goes here
    return min_value;
    // min_value is the same as your min variable. It has another name to
    // prevent name collisions
}

public static void main(String[] args) {
   int result = MyAlgorithm.min();
}
import java.util.Scanner;

public class MyAlgorithm {

    int min() {
    //(min code)
    }

    public static void main(String[] args) {
    // code here
    //corrected according to Uli's comment
        MyAlgorithm m = new MyAlgorithm();
        int result = m.min();
    }
}