Help with char and command line arguments

I am writing a program that takes 2 command line arguments (such as 4 b, or 3 4, etc.). It uses the first argument to determine the height of a triangle (how many rows high), and the second is the character with which the triangle is drawn.
My problem is I tend to code backwards - go for the bigger part and then figure out the smaller things. So, I've written a program that prints out this triangle, BUT I can't figure out how to get the command line arguments into it properly. A number works fine because I can:
size = Integer.parseInt(args[0]);
but what do I do if the second argument is a character? Args is a String array (I've been fighting with it for the past 4 hours, so I KNOW its a String array) - so how can I get a char to be read as args[1]?
Here is my code before adding in the second argument (the char):
public class Triangle
public static final void main(String[] args)
int size;
if (args.length > 0)
try
size = Integer.parseInt(args[0]);
catch(NumberFormatException e)
System.out.println("Input Error");
createFilledTriangle(size);
System.out.println();
public static void createFilledTriangle(int size)
int i = 0;
int j = 0;
for(i = size, j = 1; i > 0; i--, j +=2)
printChar(" ", i);
printChar("*", j); <-----Instead of using * I want to use the second command line arg
System.out.println();
private static void printChar(String str, int total)
for(int i = 0, i < total; i++)
if(i%2 == 1)
System.out.print(str);
else
System.out.print(" ");
Thank you for any help in advance!

I was sure i send it the other day, i probably send it to the wron guy.
This will give you more idea about drawing.
import java.awt.*;
import java.awt.event.*;
public class Args extends Frame
     Panel panel = new Tpan();
     int   arg1;
     char  arg2;
public Args(int a1, char a2) 
     super();
     arg1 = a1;
     arg2 = a2;
     setBounds(1,1,600,400);     
     setLayout(new BorderLayout());
     addWindowListener(new WindowAdapter()
     {     public void windowClosing(WindowEvent ev)
          {     dispose();
               System.exit(0);
     add("Center",panel);
     setVisible(true);     
public class Tpan extends Panel
public Tpan()
public void paint(Graphics g)
     super.paint(g);
     g.setColor(Color.blue);
     g.drawLine(120,110-arg1,80,110);
     g.drawLine(120,110-arg1,160,110);
     g.drawLine(80,110,160,110);
     g.setColor(Color.red);
     g.drawLine(120,110-arg1,120,110);
     g.setColor(Color.black);
     g.drawString(""+arg2,116,110-arg1/2+10);
public static void main (String[] args) throws InterruptedException
// get the 2 arguments from the args insread of a1= , a2=
     int  a1  = 60;
     char a2 = 'a';
     new Args(a1,a2);
Noah
import java.awt.*;
import java.awt.event.*;
public class Args extends Frame
     Panel panel = new Tpan();
     int arg1;
     char arg2;
public Args(int a1, char a2)
     super();
     arg1 = a1;
     arg2 = a2;
     setBounds(1,1,600,400);     
     setLayout(new BorderLayout());
     addWindowListener(new WindowAdapter()
     {     public void windowClosing(WindowEvent ev)
          {     dispose();
               System.exit(0);
     add("Center",panel);
     setVisible(true);     
public class Tpan extends Panel
public Tpan()
public void paint(Graphics g)
     super.paint(g);
     g.setColor(Color.blue);
     g.drawLine(120,110-arg1,80,110);
     g.drawLine(120,110-arg1,160,110);
     g.drawLine(80,110,160,110);
     g.setColor(Color.red);
     g.drawLine(120,110-arg1,120,110);
     g.setColor(Color.black);
     g.drawString(""+arg2,116,110-arg1/2+10);
public static void main (String[] args) throws InterruptedException
// get the 2 arguments from the args insread of a1= , a2=
     int a1 = 60;
     char a2 = 'a';
     new Args(a1,a2);

Similar Messages

  • Help with JNI C command line arguments

    Hi.
    I have created a .dll using c and jni which calls java classes from the .exe I have created in C. When I pass the arguments by hard-coding in the .dll file (i.e. options[0].optionString="-Djava.class.path=C:\xxx.xxx\;C:xxx\xxx usrName passwd id", it seems to work fine.
    However, I want to pass the same arguments through Visual C++ Express Edition IDE. I put the same optionString into the command arguments. It creates the JVM using those arguments, and it goes into a function that does most of the work. But, it's not finding the class eventhough it's located in the same folder otherwise the hard-coded path wouldn't work. However, after destroying JVM, it prints that the Class is found. I am also passing the .jar files as arugments using ; to separate path. Any ideas or suggestions. Please reply. Thank you in advance.
    Here is the output that I get:
    Executing the JNI_VERSION_1_2 block
    JVM Status: 0
    Version: 10004
    Going into createStuff() function now...
    Classpath is: java/sql/Timestamp
    Class Found: java.sql.Timestamp: OK
    Getting MethodID: java.sql.Timestamp <constructor>: OK
    Creating New java.sql.Timestamp class object: OK
    Classpath is: com/myCompany/myStuff/myClass
    myCls is null
    Going to Destroy...
    Destroying JVM
    Exception in thread "main" java.lang.NoClassDefFoundError: com/myCompany/myStuff/myClass
    Class Found: com/myCompany/myStuff/myClass: OK
    Press any key to continue . . .

    Yes. I am using those parameters because my java class uses that those parameters. But that's not the case. The problem is that I am not sure how to assign the whole path to options[0].optionString. If I hard-code the path that I showed you before, then it works because the path is the whole string which is assigned to the optionString. So, I am assigning the same string to the command arguments. Its just that in my createJVM(char *argv[]) function, I need to parse argv[1], argv[2], argv[3] and argv[4], and assign that to the optionString.  But I am not sure how to do that.  Any help will be appreciated.  Thanks again.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Can anyone help with Adobe_Updater.exe command line options?

    Hi,
    I am trying to run the updater silently to update Reader.
    Thanks,
    SteveJ

    Try these...
    msiexec /p <patch.msp> /qn --- silent install
    msiexec /p <patch.msp> /qb – progress bar install

  • Automate Discoverer 4.1 install; Any command line arguments?

    I'm working on automating the install of Discoverer 4.1 for use within my company. Does the setup.exe or orainst.exe take any command line arguments? Can it be configured for a default and silent install? Similiar to .msi? or Installshield setup.exes?
    Please provide any command lines or arguments or a resource for these.
    Thanks,
    Chris

    >
    I have added the needed languages to Windows, and I
    can produce the foreign characters using the keyboard.You can produce the characters in a command console window?
    But when I pass strings containing those foreign chars
    as command line arguments to a Java application, the
    chars are replaced with question marks (\u003f) when I
    get them using the args array.
    You see the question marks on the console window? Did you actually look at the char value to confirm that the value is 0x003f? Sometimes a font problem will cause ? to display even though the underlying character is still being sent to the console or GUI component.
    For instance, in a English Windows XP, I set the input
    language to be Japanese. Then, I call my simple
    application, which echoes the unicode code for each
    char in each command line argument, as well as the
    file.encoding, user.region and user.language
    properties.
    Windows has a couple of active charsets at any point in time: the file and console code page (OEM charset) and its GUI charset (ANSI charset). The file.encoding property reports the ANSI charset, not the OEM charset used in the console and file system.
    Try this: set your "system" locale to Japanese as well. This will force the console charset to be 932 as well. Type "chcp" on the console to check what windows thinks the charset is.
    John O'Conner

  • Need Help with command line arguments for a class method

    Hey guys,
    I'm fairly new to programming in java.
    I want to a write a class method that adds up its command line arguments which are numbers. For example, if the input was .... 5 2 3....then the output would be 10.
    I have been told to use the Convert to convert a string to a double. I'm ok for writing the class method but I have no idea how to use Convert and why I need it in the method.
    Can anybody help please?

    Hey guys,
    I'm fairly new to programming in java.
    I want to a write a class method that adds up its
    command line arguments which are numbers. For
    example, if the input was .... 5 2 3....then the
    output would be 10.Okay. So you would receive the numbers to add as the String[] argument to a main method. The steps are simple:
    1) declare a variable for the count
    2) for each String in the array:
    2.1) extract the value as a double
    2.2) add this to the count
    3) output the resulting count
    I have been told to use the Convert to convert a
    string to a double.
    I'm ok for writing the class
    method but I have no idea how to use ConvertThere is no class Convert in the Java API.
    and why
    I need it in the method. Do you understand you need to somehow convert each String to a double (step 2.1)? Since Convert is unknown to me, maybe you should just take a look at class Double. It can help you do step 2.1, the rest should be trivial enough.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Double.html
    Give it a go and feel free to post back with a specific problem you are having, accurately described if you please :-)

  • Executing another program with command line arguments

    I am very new to Java, so bare with me.
    I have written an encryption/decryption program in C (that accepts command line arguments of the key, mode (encrypt/decrypt), and file), and I have written a GUI for it in Java. It accepts the filename (and has a button which opens the "File/Open" dialog), key, and mode, and has a button to Start the process of the encryption. I'd like for that "Start" button to call my encryption program in C (eep.exe) with the command line arguments of the file, key, and mode. This is what I have written so far :
    Start = new JButton("Start");
    Start.setBounds(150, 180, 90, 25);
    Start.addActionListener(new ActionListener() {     
    public void actionPerformed(ActionEvent ae) {
    Desktop.open(new File("C:\\eep.exe" + " " + filename + " " + mode + " " + key));
    However, I get the error "Cannot make a static reference to the non-static method open(File) from the type Desktop" on the Desktop.open command.
    What should I do? Is Desktop.Open the right way to go about this? If not, what is the right way to go about it?
    Thanks in advance.

    That has helped greatly, but I cannot pass command line arguments to it.
    Using :
    try {
        Desktop.getDesktop().open(new File("C:\\eep.exe"));
    catch (Exception e) {
       System.out.println("Error executing.");
    }I can execute eep.exe, but when I try to pass command line arguments to it, such as
    Desktop.getDesktop().open(new File("C:\\eep.exe" + " " + filename));it fails, get caught and prints "Error Executing."
    I have also tried loading the program, as well as some command line arguments into an array of strings :
    String[] cmdArray = {"C:\\eep.exe", filename};
    Desktop.getDesktop().open(new File(cmdArray));But it gives me the error "The constructor File(String[]) is undefined" on the
    new File (cmdArray)part of the command.

  • Pass the command line argument (argc and argv) to a LabVIEW built shared library.

    Hello,
    I have successully use this trick to build a LabVIEW application that runs on Linux without X Display.
    http://digital.ni.com/public.nsf/allkb/5D6EC36DCF43343786257449006919E6
    I'd like to know if it's possible to pass the command line arguments ( ./TEST A B C D) directly into the shared library without having to pass the arguments using a array of strings which would require to write code using DSNewHandle, DSSetHandleSize, extract the arguments and ..... (I'm not proficient in C, but if I don't have a choice I will do it and improve my C skills).
    int main(int argc, char *argv[])
            Test(argc, argv);
            return 0;
    Thanks,
    Michel
    Solved!
    Go to Solution.

    Well, you can always flatten it back into a space separated single string and pass it like that. Basically reverse what the OS does when it calls your main function with the command line parameters. And while the first element in the array is always the program name itself you can just skip that here, but then format all the rest into a single string.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Problem associated with Command Line arguments

    hi ,
    I am not able to pass a file path as command line argument in java.
    Actually i want to run a java program from the command prompt passing a file path . Something like this i tried to do , but its not working.
    D:\VISHAL\src> java CopyFile C:\Documents and Settings\Administrator\Desktop\link.txt
    where ,
    CopyFile is the name of my class which i am going to run
    C:\Documents and Settings\Administrator\Desktop\link.txt is the argument.
    Can anyone tell me whether a java program accepts an argument like this, if yes please tell me the exact syntax..
    Thanks
    Vishal J
    Message was edited by:
    vishal_vj

    is there any other way of solving this?Y don't U try it out with the logic as mentioned
    below it wud be the case if U r not going with
    java CopyFile "C:\Documents and
    Settings\Administrator\Desktop\link.txt" 1
    String filepath = new String();
    for(int i = 0; i < Arg.length; i++)
    filepath.append(Arg);
    File f = new File(filepath);
    What????  This is a non-solution to a non-problem.  First of all, you would be constructing a filename without spaces, when the real path contains spaces.  Secondly, even if you did insert spaces it would not matter.  What if the String (and it does not have to be a filename) contained tabs rather than spaces.  The real (and really only) solution to the problem is to put quotes around the argument, for the exact reason stated in my last post.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How To Run An External .exe File With Command Line Arguments

    Hiya, could anyone tell me how I can run an external .exe file with command line arguments in Java, and if possible catch any printouts the external .exe file prints to the command line.
    Thanks.

    Using the Runtime.exec() command. And read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Error message in scanning:"The scanning software was launched with improper command- line arguments"

    We have downloaded and installed the HP Photosmart full feature Sostware and Drivers to Photosmart C3183 All-in-one.
    Click the Scan document in Solution Center-
    Error message displayed:
    The scanning software was launched with improper command-line arguments"
    Extended error information: 8,[(-1,0,0)]
    When Hp scan diagnostic utility  was used  - the message was: no scanners installed.
    how can we resolve the scanning problem
    nidataytay

    I have the same problem on a HP 5610 Officejet All-in-One.
    "The scanning software was launched with improper command-line arguments.
    8, [(-1, 0, 0)]"
    What is the solution? The scanner does not work. All other functions, print, fax, copy work from with in the HP Solutions Center software - but not the scanner.

  • Command line arguments with a Labview pda applicatio​n

    Hi Everyone,
    I am in the process of writing some Labview code to run on a PDA that is called from another vendor's software. When called, I need to pass some information to it (in the form of an integer) and then return an error code when it has finished its task (again, as an integer).
    Not being able to compile a my application as a labview dll for to run on a PDA with Windows Mobile 2003, I was hoping to be able to pass command line arguments to my program when compiled as an executable. This doesn't seem to be possible.
    Could someone please confirm that Labview PDA applications do not support command line arguments?
    Any suggestions on how to meet my objective would be most welcome .
    Regards,
    Mark

    Paolo,
    Thanks for your input: storing this information in a text file is a choice we are looking at. But it does leave us with the problem that the vendor's software will not necessarily know when our program has finished running, unless it continuously polls the file to see if there has been any update.
    A dll would be ideal. I was hoping there might be a clever way of emulating this.
    Regards,
    Mark.

  • Using Command Line Arguments with JAVA

    Hi,
    we are using an app called ImageMagick to scale and modify images before they are uploaded to a webserver.
    ImageMagick is called from our Objectiv-C app via
    command line.
    is there a way to this in Java?
    Regards
    Eckbert

    So, ur question is not developing a Java application that
    will do the 'image conversion'; but, your message
    conveys that u want to know how to invoke a Java program built by 'imagemagick' that takes command line arguments?
    Am I right?
    If that's the case, u must look into the documentation
    given along with the download'ed piece of software
    for identifying the 'starting point of the program'. i.e., the
    class that contains the 'main' method! And after you
    identify that class [Eg. ImageMagickStart] then you'll
    have to invoke as follows:
    [you must have Java installed in ur system!]
    c:>java ImageMagickStart
    If the program was written intelligently it must print all
    the command-line arguments required by the above
    program by executing the above command, and from that
    you can identify!
    -RK

  • Error while running aiaconfig.sh - The command line argument(s) "weblogicConfig"

    Hi.
    We are Configuring PIP on AIA 11.1.1.7 after installing AIA PIP release. we we run ./aiaconfig.sh we are getting below error message,
    $./aiaconfig.sh
    Starting Oracle Universal Installer...
    Checking swap space: must be greater than 500 MB.   Actual 169130 MB    Passed
    Checking monitor: must be configured to display at least 256 colors.    Actual 16777216    Passed
    Preparing to launch Oracle Universal Installer from /tmp/OraInstall2013-11-20_04-11-10AM. Please wait ...adevaia                                                        @soa-odi-dev1:/u02/app/Oracle/Middleware/AIAHOME/bin$ [WARN ][jrockit] MaxPermSize=256m ignored: Not a valid opt                                                        ion for JRockit
    Log: /u01/app/oraInventory/logs/install2013-11-20_04-11-10AM.log
    The command line argument(s) "weblogicConfig" or the install mode specified is not valid.
    Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
    Usage:
    config.sh [-mode] [-options] [(<CommandLineVariable=Value>)*]
    Where mode include:
    [Mode is a mandatory parameter. Only one mode can be specified.]
         -silent For silent mode operations, the inputs can be a response file or a list of
                  command line variable value pairs.
    Where options include:
         -help, --help, --usage
                  Displays above usage.
         -invPtrLoc <inventory pointer file>
                  Launches the installer with a custom inventory location. The invPtrLoc
                  should point to a file which contains the following information.
                  inventory_loc=<inventory_location>
                  inst_group=<group_name>
         -response, -responseFile <response file>
                  Specifies the response file and path to use.
         -jreLoc <location>
                  Path where Java Runtime Environment is installed. OUI cannot be run without
                  it.
         -logLevel <level>
                  To filter log messages that have a lesser priority level than <level>.
                  Valid options are: severe, warning, info, config, fine, finer, finest,
                  basic, general, detailed, trace. The use of basic, general, detailed, trace
                  is deprecated.
         -debug  For getting the debug information from OUI.
         -force  Allowing silent mode installation into a non-empty directory.
         -printdiskusage
                  Log debug information for disk usage.
         -printmemory
                  Path where Java Runtime Environment is installed. OUI cannot be run without
                  it.
         -printtime
                  Log debug information for time usage.
         -waitforcompletion
                  For windows. setup.exe will wait for completion instead of spawning the
                  java engine and exiting.
         -noconsole
                  For suppressing display of messages to console. Console is not allocated.
         -ignoreSysPrereqs
                  For ignoring the results of the system pre-requisite checks.
         -executeSysPrereqs
                  Execute system pre-requisite checks and exit.
         -paramFile <location of file>
                  Specify location of oraparam.ini file to be used by OUI.
         -novalidation
                  Disables the validations, can be invoked along with GUI or silent mode.
         -nodefaultinput
                  Disables the default computation of values (pre-populating of values when
                  screen is loaded) in GUI install.
         -nocheckForUpdates
                  To disable all updates checking
         -updatesDir
                  To specify the directory where latest updates are downloaded. This could be
                  used in disconnected mode.
    Command Line Variables Usage:
              Command line variables are specified using <name=value>; for example:
                  [ session: | session:compName: | session:compName:version: ]variableName=" valueOfVariable"]
              Installer variables are specified using:
                  varName=value
                  Ex: ORACLE_HOME=<value>
              OUI Session variables are specified using:
                  session:varName=value
                  Ex: session:VARIABLE_NAME=<value>
              OUI Component variables are specified using:
                  session:compInternalName:[Version:]varName
                  Ex 1: session:oracle.comp1:1.0.1:varName=<value>
                  Ex 2: session:oracle.comp1:varName=<value>
                  The lookup order is compInternalName:Version:varName, then compInternalName:varName
    do anyone had any idea on this.
    Thanks a lot,
    RR.

    try checking relevant environment variables like the CLASSPATH.... a major source of failures in Windows is when in the classpath there is a path containing SPACES.... also enabling some "debug" or "verbose" flag (not sure how to do it) would provide more insight...

  • Error message: "invalid command line argument" while lodaing itunes

    I'm trying to load Itunes onto a computer that already has a version of itunes on it. I get a message that says "error: -1639 invalid command line argument" Does anyone know what this means? Does this mean I can't load itunes onto a computer that already has itunes on it?
    Also, I was able to load itunes on my laptop, but My ipod Icon is not appearing anywhere, not in itunes, not in explorer, not in my computer. I am, however, able to transfer music automatically when I plug the Ipod into the laptop. I have created several playlists and they have transferred over to the ipod as playlists. Any ideas why I can transfer despite not being recognized anywhere on the computer?
    Last thing is, I have plugged the Ipod into three different computers with itunes on them, and the ipod does not show up in the source list.
    I'm somewhat perplexed by all of this. Any help or insight would be greatly appreciated
    Dell   Windows XP Pro  

    hiya!
    "error: -1639 invalid command line argument"
    hmmm. folks typically only get that error if they are installing from removable media (such as a CD), although i have seen it happen if someone tries to install into the "recovery partition" of certain makes of PC.
    if you download and save an installer to your C drive and run the install from there, do you still get the 1639?
    iTunes 6.0.4.2 Installer
    love, b

  • ERROR: -1639 INVALID COMMAND LINE ARGUMENT

    Trying to install software for Shuffle that Santa brought and get this error messsage...
    "Error: -1639 invalid command line argument. Consult the windows Installer SDK for detailed command line help."
    Install stops at this point.
    SOMEONE HELP... My kid is chomping at the bit !
    Thanks.

    Ok I'll do some more searching but I found something in the community forums.
    APPSearch can not return this data into a property, so instead, for some unspeakable reason, returns a value of Null, follwed by another Null. This means that the property is created, and populated with two null characters. Bad news if the property also happens to be a PUBLIC property. All public properties are passed as part of the command line sent in a stream to the background installer process by the Execute Action. Since this stream now contains a double null value in a property, the stream is prematurely terminated. This creates an invalid command line, and thus the 1639 error.
    This user solved it by using the MSi Cleanup installer util.
    EDIT: A little more info...
    This problem is almost impossible to detect through the MSI log files since our friends at Microsoft chose to limit the length of any line in the log. It is impossible to get a dump of the full command line that generates this error.
    EDIT2:Note that error 1639 only ocurrs when the install package is run from removable media. When the package is run from local storage, the behavior is far more obtuse. The background install process, failing to receive a complete command line, is forced to run as if there had been no UI session, which in turn causes the APPSearch action to run again as if the install was running in silent mode. This causes re-evaluation of all properties a second time, destroying the feature selections made in the UI session, and also forcing the install to run under user credentials instead of elevated, even though AdminUser, ALLUSERS and Privleged properties are set. This is a very serious error that causes total failure of the installation.

Maybe you are looking for

  • N97 can send but not receive Yahoo emails. Secure ...

    Hi all, I promise i have looked through the other answers on here but not tell me precisely what to do. 1. Went to Yahoo and activated POP & Forwarding 2. Double checked Incoming and Outgoing servers i.e. pop.mail.yahoo.co.uk   SSL Port 995  and smtp

  • Application Development Directory Structure

    I work with a team consisting of five programmers who want to rewrite a suite of software developed in C/C++ to Java. This will consist of numerous application programs; none of which are web-based. We use the UNIX OS and will access an Oracle databa

  • Adding a Custom field in Catalog

    Hi, We are implementing a new catalog and we are using the SRM 4.0. We need to add one more custom field to get the Information related to CAS number in the Front end. How can we add the new field in the SRM and match with the corresponding Vendor ca

  • Toshiba Tecra M9 Bios problem

    Hi, Cant change in Tecra M9 bios boot from cd or flash. PgUp and PgDn not working there, buttons work in all other aplication in windows except Bios. HDD now formated, cant setup anything to PC.

  • N95 Music Player

    I've noticed this a few times, but its really started to annoy me. How come when I have a playlist on my N95 and I set it to shuffle - it doesnt play ALL the songs? If I have a playlist with 10 songs it will only play a few and then stop. Today I set