RUVIDEO
Поделитесь видео 🙏

How to input from keyboard through Command-line Argument in Java(in Eclipse IDE )?

📁 Обучение 👁️ 16 📅 05.12.2023

Today we are going to learn how to take command line argument in Eclipse IDE

What is Command line argument?

The command-line argument is an argument i.e., passed at
the time of running the Java program to the main method.

The arguments passed from the console can be received
in the Java program and it can be used as an input.

You can pass N (1,2,3 and so on) numbers of arguments
from the command prompt with spaces (blank characters)
between each value.

The command-line arguments can be found in the String array
called args.Note that the argument is an array of strings.

In C and C++, argv[0] is the name of the program itself,
and argv[1] is the first command-line argument to the program.
In Java, args[0] is the first command-line argument to the
program, and the name of the program itself is not available.

If a Java program requires numeric command-line arguments, it
must explicitly convert the string version of the number into
the actual numeric value. e.g.,

num = Integer.parseInt(args[0]);

Here is the primitive data-types, and functions you can use for
parsing command-line arguments of those types. These classes are
in the java.lang package, so they are available without needing
to specify any import statements in your Java programs. Also, the
parsing functions are static, so you don't need to create any new
objects to use these functions.

Primitive Data Type : Parsing Function
------------------------------------------------------------------
boolean--------------------------boolean Boolean.parseBoolean(String)
int----------------------------------int Integer.parseInt(String)
long-------------------------------long Long.parseLong(String)
float-------------------------------float Float.parseFloat(String)
double---------------------------double Double.parseDouble(String)


Note:
--------
public static void main(String[] args) {
int num = 0;
...
try {
// Parse the string argument into an integer value.
num = Integer.parseInt(args[0]);
}
catch (NumberFormatException nfe) {
// The first argument isn't a valid integer. Print
// an error message, then exit with an error code.
System.out.println("The first argument must be an integer.");
System.exit(1);
}
... // Code that uses the command-line arguments.
}

The most important point is that you must handle invalid inputs!
The number parsing functions will throw a java.lang.NumberFormatException
when parsing fails. Your programs should not crash when they receive invalid input.Instead, catch the exception, print out a helpful message, and then exit your program with a non-zero error code.

The second important point about this code is that num is declared and initialized before the try/catch block.The variable must be declared before the try/catch block because it will be used after the block completes; if it is declared within the block, it will only be visible within the block.The variable must be initialized before the try/catch block because otherwise, the Java compiler will report an "uninitialized variable" error at compilation.

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «How to input from keyboard through Command-line Argument in Java(in Eclipse IDE )?», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.