我正在尝试将主程序“String [] args”转换为5个整数和4个双精度数。 (我知道这有点令人困惑)
我想这样做的方法是让一个forreach循环循环遍历String args []并将它们添加到一个int数组(对于前5个),但是我必须用于数组,所以它没有'工作。
if (args != null) {
// If arguments where given, use the arguments and run the program
// NEED TO SOMEHOW CONVERT ARGS INTO INTEGER FORM AFTER BEING PASSED IN
ArrayList<Integer> valArr = new ArrayList<Integer>(10); // could be 9
for (String val : args) {
// Parse the string and add it to valArray
int temp = Integer.parseInt(val);
valArr.add(temp);
}
CarPark cp = new CarPark(valArr[0], valArr[1], valArr[2], valArr[3]);
这就是我现在正在看的......我完全错了吗?还是关闭?
答案 0 :(得分:1)
只需使用两个索引for
循环解析它。
int[] myInts = new int[5];
double[] myDoubles = new double[4];
// Initialize these arrays with "defaults" here.
// Notice how we handle the possibility of the user not entering enough values.
for (int i = 0; i < Math.min(5, args.length); i++)
myInts[i] = Integer.parseInt(args[i]);
for (int i = 0; i < Math.min(4, args.length - 5); i++)
myDoubles[i] = Double.parseDouble(args[i+5]);
CarPark cp = new CarPark(myInts[0], myInts[1], myInts[2], myInts[3]);
答案 1 :(得分:0)
你必须从数组列表中获取值,如下所示
CarPark cp = new CarPark(valArr.get(0), valArr.get(1), valArr.get(2), valArr.get(3));
答案 2 :(得分:0)
以上可能是这样的
CarPark cp = new CarPark(valArr.get(0), valArr.get(1), valArr.get(2), valArr.get(3));
答案 3 :(得分:0)
我认为这应该有效。
if (args != null) {
// If arguments where given, use the arguments and run the program
// NEED TO SOMEHOW CONVERT ARGS INTO INTEGER FORM AFTER BEING PASSED IN
ArrayList<Integer> valArr = new ArrayList<Integer>(10); // could be 9
for (String val : args) {
// Parse the string and add it to valArray
int temp = Integer.parseInt(val);
valArr.add(temp);
}
CarPark cp = new CarPark(valArr.get(0), valArr.get(1), valArr.get(2), valArr.get(3));
答案 4 :(得分:0)
以下是您更正后的代码: -
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
args=new String[4];
for(int i=0;i<4;i++){
System.out.println("Enter value no- "+(i+1));
args[i]=sc.nextLine();
}
ArrayList<Integer> valArr = new ArrayList<Integer>(10);
if (args != null) {
// If arguments where given, use the arguments and run the program
// NEED TO SOMEHOW CONVERT ARGS INTO INTEGER FORM AFTER BEING PASSED IN
// could be 9
for (String val : args) {
// Parse the string and add it to valArray
int temp = Integer.parseInt(val.trim());
valArr.add(temp);
}
}
System.out.println(valArr);
//CarPark cp = new CarPark(valArr[0], valArr[1], valArr[2], valArr[3]);
}
}
这只是Integer部分的代码,类似于扩展args数组长度并包含double值,Remeber使用val.trim()删除空格,否则会抛出NumberFormatException。