[英]How to get user input in java programs in vs code without using public static void main (String[]args)
Can anyone please help me how to get user input in java programs in vs code without using public static void main (String [] args)任何人都可以帮助我如何在不使用public static void main (String [] args) 的情况下在 vs 代码中获取 Java 程序中的用户输入
I can safely do this thing using method call in BlueJ ide but couldn't figure out how to do this in vs code or any other ides....我可以使用BlueJ ide 中的方法调用安全地做这件事,但无法弄清楚如何在 vs 代码或任何其他 ide 中做到这一点......
Here is the simple code that I want to run--这是我想运行的简单代码——
public class Rectangle
{
public static void main (int l, int b)
{
int area, peri;
area = l*b;
peri = 2*(l+b);
System.out.println("Area = "+area);
System.out.println("Perimeter = "+peri);
}
}
There isn't a practical alternative if you are writing a stand-alone command line application in Java.如果您正在用 Java 编写独立的命令行应用程序,则没有实用的替代方案。
There are various libraries for command line argument parsing in Java, but (AFAIK) they all require you to write a public static void main (String [] args)
method .... even if it is just simple boilerplate code. Java 中有各种用于命令行参数解析的库,但是(AFAIK)它们都要求您编写一个public static void main (String [] args)
方法......即使它只是简单的样板代码。
(This is not true for all kinds of Java application. For example webapps in a web container, JavaFX applications, or ... applets) (这不适用于所有类型的 Java 应用程序。例如 Web 容器中的 webapps、JavaFX 应用程序或...小程序)
You cant run a program with out main program. Execution always starts from main program.Your IDE may automatically generate main program, But if you are looking for an alternative way of ( other than command line argument) getting input you can use Scanner or any input stream methods
import java.util.Scanner
public class Rectangle
{
public static void main(String arg[])
{ Scanner myObj = new Scanner(System.in); // Create a Scanner object
int l= myObj.nextInt(); // Read user input
int b=myObj.nextInt();
int area = l*b;
int peri = 2*(l+b);
System.out.println("Area = "+area);
System.out.println("Perimeter = "+peri);
}
}
You can't not do that.你不能不这样做。
As described here a java application entry point has to be public static void main(String[] args)
.如此处所述, java 应用程序入口点必须是public static void main(String[] args)
。
This makes sense.这是有道理的。 The parameters from the command line arguments are Strings, not matter what.命令行参数中的参数是字符串,无关紧要。 To make int
out of it, there would be an implicit conversion.为了使int
脱离它,将有一个隐式转换。 Where do you catch parsing errors for that if it happens before it reaches your code?如果它在到达您的代码之前发生,您在哪里捕获解析错误?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.