簡體   English   中英

使用從命令行發送的參數運行程序

[英]Running a program with argument sent from command line

我需要程序采用String參數並將字符拆分。 然后,我想將這些單獨的字符添加到ArrayList中,並打印出列表,其中每個單獨的字符都位於彼此下面。

import java.util.*;
import java.io.*;

public class Main {

public static void main(String[] args) {
    try{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter argument:");
        String input = br.readLine();
        String value = "";

        ArrayList al = new ArrayList();

        for(int i = 0; i < input.length(); i++){
            value = "" + input.charAt(i);
            al.add(value);
        }

        Iterator it = al.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
            it.remove();
        }

    }catch(IOException e){
        System.out.println(e.toString());
    }
}

}

該參數應來自命令行,例如:java myApp Lesley

提前致謝

import java.util.*;
import java.io.*;

public class Main {

public static void main(String[] args) {
    try{
        String input = String.valueOf(args[0]);//assuming there will always be an input from command line
        String value = "";

        ArrayList al = new ArrayList();

        for(int i = 0; i < input.length(); i++){
            value = "" + input.charAt(i);
            al.add(value);
        }

        Iterator it = al.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
            it.remove();
        }

    }catch(IOException e){
        System.out.println(e.toString());
    }
}

}

嘗試這個

這些參數像VD一樣存儲在String[] args數組中...但是如果有參數,則應檢查args數組

If (args.length != 0) {
    do something
}

編輯:如果您使用命令行運行程序,則必須先使用

javac pathtofile

比你可以使用的

java pathtofile

你為什么這么難?

if(input.contains("java myApp Lesley"){
window.window();                       //new class where u create the window
}

命令行參數通過其參數String[] args傳遞給main方法。 由於那對調用您的程序並不總是很明顯,因此它的好風格可以在缺少參數的情況下給出提示。 例如:

if (args.length == 0) {
    System.out.println("Usage: myApp <Name>");
}
else {
    // your code here using args[0]
}

如果您使用多個命令行參數,請相應地更改檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM