[英]How can I get an ssh key data from a command line argument in java program?
[英]Getting an error running this program as a command line argument in Java, how can I fix this?
嘗試在Eclipse中作為命令行參數運行該程序時出現錯誤。 這是錯誤的意思:
錯誤:在類中找不到主要方法,請將該主要方法定義為:public static void main(String [] args)或JavaFX應用程序類必須擴展javafx.application.Application
當我將main方法更改為String時,我無法調用第二個方法,因為String main方法與int returnSum方法不兼容。
我需要根據要求將returnSums方法設置為int類型的方法,但我無法弄清楚如何做到這一點而不會出錯。 它說,在需求中,我需要為方法使用可變數量的參數,但是很難理解這個想法。
有人可以幫我嗎? 這是我的代碼:
public static void main(int[] args) {
// Printing the entered digits
System.out.print("Passing");
System.out.print(" [ ");
for (int nums = 0; nums < args.length; nums++) {
System.out.print(args[nums] + " ");
}
System.out.print("] ");
System.out.println("\nSum is " + returnSum(args)); // Calling on the second method for the sum
}
// Taking the nums from the main method as arguments
public static int returnSum(int...args) {
int sum = 0;
// Calculating the sum
for (int nums = 0; nums < args.length; nums++) {
sum = sum + nums;
}
return sum;
}
謝謝!
嘗試以下代碼:
public class SumOfNumbers {
public static void main(String[] args) {
int[] intArgs = new int[args.length];
for (int x = 0; x < args.length; x++) {
if (args[x].matches("\\d+")) {
intArgs[x] = Integer.parseInt(args[x]);
} else {
System.out.println(args[x] + " is not a Integer hence skiped in this program");
}
}
// Printing the entered digits
System.out.print("Passing");
System.out.print(" [ ");
for (int nums = 0; nums < intArgs.length; nums++) {
System.out.print(intArgs[nums] + " ");
}
System.out.print("] ");
System.out.println("\nSum is " + returnSum(intArgs)); // Calling on the second method for the sum
}
// Taking the nums from the main method as arguments
public static int returnSum(int... args) {
int sum = 0;
// Calculating the sum
for (int nums = 0; nums < args.length; nums++) {
sum = sum + args[nums];
}
return sum;
}
}
@Sanjay:如果嘗試使用參數: 10, 20 , 30
則會得到以下輸出:
10, is not a Integer hence skiped in this program
, is not a Integer hence skiped in this program
Passing [ 0 20 0 30 ]
Sum is 50
10,不應僅被忽略,應被忽略。 並且它的intArgs的大小應為3(包括10)或大小為2(不包括10),其大小不應為4。
將主方法的參數更改回String[]
,因為這是必需的簽名。
在您的main方法中,將每個參數解析為一個int
:
int[] intArgs = new int[args.length];
for(int x=0; x<args.length; x++)
intArgs[x] = Integer.parseInt(args[x]);
請注意,如果不傳遞任何參數或非整數的參數,則此參數將中斷。 如果要處理此問題,可以先檢查args!=null
並在此代碼附近捕獲NumberFormatException
。
您將需要使主方法簽名為(String[] args)
但是您可以循環遍歷代碼中的args
數組,使用Integer.parseInt()
將每個元素轉換為int
,並將它們存儲在新數組中(類型int[]
),然后將此新數組發送到returnSum
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.