[英]When i call the method f() nothing appears in the console. Why?
package Evaluare1;
import java.util.*;
public class e15 {
public static void main(String[]args){
Scanner s = new Scanner(System.in);
int a = s.nextInt();
f(a);
//i don't have errors when i run it
}
//this method won't return the value when i call it
public static int f(int x){
if(x%2 <= 0){
return x/2;
}else
return x * 3 + 1;
}
}
How can I fix this?我怎样才能解决这个问题?
If what you want to do is print the result of f()
than you cannot simply invoke the function as all that will do is return the result, which you are ignoring.如果您想要做的是打印f()
的结果,那么您不能简单地调用该函数,因为所有要做的就是返回您忽略的结果。 Instead try something like this:而是尝试这样的事情:
import java.util.*;
public class e15 {
public static void main(String[]args){
Scanner s = new Scanner(System.in);
int a = s.nextInt();
System.out.println(f(a));
//i don't have errors when i run it
}
//this method won't return the value when i call it
public static int f(int x){
if(x%2 <= 0){
return x/2;
}
else
return x * 3 + 1;
}
}
Note the System.out.println(f(a));
注意System.out.println(f(a));
. . This will print your result to standard out, typically your shell.这会将您的结果打印到标准输出,通常是您的外壳。
添加 System.out.println() 以在控制台上打印。
If you are trying to learn java try to use different methods present in the PrintStream.class如果您正在尝试学习 Java,请尝试使用 PrintStream.class 中存在的不同方法
For example,例如,
public class e15 {
public static void main(String[]args){
Scanner s = new Scanner(System.in);
int a = s.nextInt();
System.out.print(f(a));
//i don't have errors when i run it
}
//this method won't return the value when i call it
public static int f(int x){
if(x%2 <= 0){
return x/2;
}else
return x * 3 + 1;
}}
In this I have used the print function present in the PrintStream class, it prints the particular integer (overloaded method), you could also use printf, where you want to insert the value at the exact position of the string without concatenation, use %s for string %d for Numbers like that.在此,我使用了 PrintStream 类中存在的打印函数,它打印特定的整数(重载方法),您也可以使用 printf,您想在字符串的确切位置插入值而不连接,使用 %s对于字符串 %d 这样的数字。
The advantages of println is that it prints in the new line. println 的优点在于它在新行中打印。
Play around it would be fun.玩它会很有趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.