The goal of this assignment is • To learn how to use command line arguments Your
ID: 3871321 • Letter: T
Question
The goal of this assignment is
• To learn how to use command line arguments Your task is to write an application that prints stars (*) or dollar signs ($) depending on the command line argument. The first command line argument must be a string of “star” or “dollar”. The second command line argument is the the number of the symbols to be printed in total. The third command line argument is the number of the symbols to be printed in a line. If the argument values are not valid, print the usage and quit the application. See Fig 7.21 to see how you can convert a string to an integer. Your code must compile from the windows command line using the following commands.
javac PrintSymbols.java
Example command and output
> java PrintSymbols star 7 3
* * *
* * *
*
> java PrintSymbols dollar 9 5
$ $ $ $ $
$ $ $ $
> java PrintSymbols comma 10 2
Usage: java PrintSymbols [star|dollar] number_of_symbols number_of_symbols_per_line
> java PrintSymbols star 10
Usage: java PrintSymbols [star|dollar] number_of_symbols number_of_symbols_per_line
Explanation / Answer
public class PrintSymbols
{
public static void main( String[] args )
{
int total=0,line=0,k;
String s1 = "star";
String s2 = "dollar";
boolean flag = false;
if(args.length != 3)
flag = true;
try{
total = Integer.parseInt(args[1]); //taking in an integer input throws NumberFormat Exception if not an integer
line = Integer.parseInt(args[2]);
}
catch(NumberFormatException e)
{
flag = true; //is input is not an integer, occurs while parsing the command line input argument
}
catch(ArrayIndexOutOfBoundsException e)
{
flag = true; //as takes in input from command line which is stored to a Args array in main, if this array is null implies no input given
}
//total = Integer.parseInt(args[1]);
//line = Integer.parseInt(args[2]);
if(args[0].equals(s1) == true && !flag)
{
while(total >= line)
{
for(k=0;k<line;k++)
System.out.print( "* ");
System.out.println("");
total = total - line;
}
if(total > 0)
{
for(k=0;k<total;k++)
System.out.print( "* ");
System.out.println("");
}
}
else if(args[0].equals(s2) == true && !flag)
{
while(total >= line)
{
for(k=0;k<line;k++)
System.out.print( "$ ");
System.out.println("");
total = total - line;
}
if(total > 0)
{
for(k=0;k<total;k++)
System.out.print( "$ ");
System.out.println("");
}
}
else
{
System.out.println( "Usage: java PrintSymbols [star|dollar] number_of_symbols number_of_symbols_per_line" );
}
System.exit( 0 ); //success
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.