Java 如何正确调用多个函数?
我必须编写一个程序,其中有这三个方法/函数(我很难区分这两个lol,为此我重命名了它们): 我知道要调用这些函数,我需要在代码的底部创建一个main方法(正确吗?),但我不知道如何处理这个特定的程序。我知道它的格式是:funcName(parameters) 但我有点搞不清楚我为每一个都输入了什么参数。对于第一个方法,它应该返回所有输入的运行总数。对于第二个,我不确定该放什么,因为它正在使用(String parseString),但它应该做与第一个相同的计算。对于第三个函数,它应该从文件中读取数据,并对其中的任何实数求和 我已经为每个方法编写了代码,但最后一步是使用main方法调用函数。以下是我所拥有的:Java 如何正确调用多个函数?,java,Java,我必须编写一个程序,其中有这三个方法/函数(我很难区分这两个lol,为此我重命名了它们): 我知道要调用这些函数,我需要在代码的底部创建一个main方法(正确吗?),但我不知道如何处理这个特定的程序。我知道它的格式是:funcName(parameters) 但我有点搞不清楚我为每一个都输入了什么参数。对于第一个方法,它应该返回所有输入的运行总数。对于第二个,我不确定该放什么,因为它正在使用(String parseString),但它应该做与第一个相同的计算。对于第三个函数,它应该从文件中读取
public static double main (String[] args) {
func(Scanner input);
func(String parseString);
funcInFile(String filename);
如果我保持这样,它会给我错误,所以我知道我可能必须更改参数。谢谢大家! 不清楚您想要实现什么,但下面是根据您的问题和我对您可能要寻找的内容的理解起草的代码片段 导入java.util.Scanner; 公共类多功能调用{
public static void main(String... args){
MultiFunCall obj = new MultiFunCall();
Scanner input = new Scanner(System.in);
obj.func(input);
obj.func("Some String Value");
obj.funcInFile("file.txt");
}
public void func(Scanner input){
}
public void func(String parseString){
}
public void funcInFile(String filename){
}
}我可以帮你一点忙:-)
我也是Java/Kotlin新手,但我认为这应该是正确的
来自谷歌:一个方法,就像一个函数,是一组执行任务的指令。不同之处在于,方法与对象关联,而函数与对象不关联
程序(Java)始终使用以下方法启动:
public static void main(String[] args) {
//here is your Code
}
我不知道如何转换字符串funcInFile(String)并得到返回值double。。但我想你有你的密码
我的例子:
public class test {
public static void main(String[] args) {
double convertedString;
String doubleString = "3.5";
//Here i call my Methode(Function)
// i give my function a String ("3.5") and get back a double (3.5d)
convertedString = stringToDouble(doubleString);
System.out.println("My Double is: " + convertedString);
System.out.println("---------------- ");
// a String how is not possible to convert
// i give my function a String ("a1.0") and get back the Error(Exception)
doubleString = "a1.0";
convertedString = stringToDouble(doubleString);
System.out.println("My WrongDouble is: " + convertedString);
}
private static double stringToDouble(String number) {
double doubleNumber;
//Try Catch if something goes wrong
try {
//makes a Double to a string
doubleNumber = Double.parseDouble(number);
} catch (NumberFormatException e) {
System.out.println("This String is not possible to Pars to a double");
System.out.println(e);
System.exit(0);
}
return doubleNumber;
}
}
输出:
My Double is: 3.5
----------------
This String is not possible to Parse to a double
java.lang.NumberFormatException: For input string: "a1.0"
Process finished with exit code 0
不清楚你想做什么。您是否正在尝试使用扫描仪获取用户输入并解析该字符串,然后写入文件?欢迎使用StackOverflow,这是一个问答网站而不是教程网站。您的问题表明,在继续之前,您可能需要多复习一下Java语法,我建议您在这里提问之前多自学一下。
My Double is: 3.5
----------------
This String is not possible to Parse to a double
java.lang.NumberFormatException: For input string: "a1.0"
Process finished with exit code 0