Day9 : Accepting Input

 Accepting Input

We can take input by the user by three method : 
  1. Using Command line Argument
  2. Using Scanner class
  3. Using GUI control

1) Using Command Line Argument

When we are giving an argument at the time of execution after compiling a program in command prompt then we use command line argument.

class Test
{
public static void main(String[] args)
{
System.out.println("Hello "+args[0]);
System.out.println("Thank You");
}
}

How to Run:
  • Open the notepad with Run as Administrator.
  • Copy Paste the above code
  • Save in bin file(if path is not specified)
  • Open command prompt with Run as administrator.
  • Enter the file location with cd command like as cd C:\Program Files\Java\jdk-17.0.4.1\bin then press Enter button
  • Then write command javac File_name.java(Example javac Test.java) then press Enter button.
  • Now our program is easily compiled.
  • We're ready to run the above code with this command java Test any_String (Example java Test SCA_Notes) and then press the Enter Button.
  • Like Output is shown below in photo..

Exception while using command line Argument : 

class Test
{
public static void main(String[] args)
{
System.out.println("Hello "+args[0]);
System.out.println("Hello "+args[1]);
System.out.println("Thank You");
}
}


Actually in the above code, if we declare as index of args as 0 and 1 then you must give input for both argument otherwise it throw an error called Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException.

Converting string to int :

Method : parseInt(String in number)
Class : Integer
Nature : Static
Syntax: Integer.parseInt(" ")

Example:
int a,b;
a = "10";
a = Integer.parseInt("10");
b = "20";
b = Integer.parseInt("20");

//Write a program to add two number taking from the user by using command line argument.

class Sumoftwonumber
{
public static void main(String [] args)
{
int num1, num2;
num1 = Integer.parseInt(args[0]);
num2 = Integer.parseInt(args[1]);
System.out.println("The Sum of num1 and num2 is " +(num1+num2));
}
}

Output : if we take num1 is 10 and num2 is 20 then get as 30.

Converting string to double:

//Write a program to add two number taking from the user by using command line argument.

class Sumoftwonumber
{
public static void main(String [] args)
{
double num1, num2;
num1 = Double.parseDouble(args[0]);
num2 = Double.parseDouble(args[1]);
System.out.println("The Sum of num1 and num2 is " +(num1+num2));
}
}
Output: If we take as an input of num1 is 5.6 and num2 is 2.9 then the required result is 8.5.



Comments

Popular posts from this blog

Day2 : Compiling Java Program with Examples

Day1: Introduction to Java and its feature

What does System.out.printf( "%-15s%03d\n", s1, x) do?