![](/img/trans.png)
[英]How to access and/or read command line arguments from a separate file inside the run method of a thread (java socket programming)
[英]Java invoking command line arguments from the main method to a separate method
我如何优化此代码以从 main 方法中获取String[] games
值并拥有一个单独的方法: public static int points(String[] games)
。 我对 Java 非常陌生,并不真正了解如何调用方法。
public class TotalPoints {
public static void main(String[] args) {
String[] games = {"1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"};
int sum = 0;
int matches = 10;
int x = 0;
int y = 0;
for (int i = 0; i < games.length; i++) {
String[] pieces = games[i].split(":");
x = Integer.parseInt(pieces[0]);
y = Integer.parseInt(pieces[1]);
}
for (int j = 0; j < matches; j++) {
if (x > y) {
sum = sum + 3;
} else if (x == y) {
sum = sum + 1;
}
}
System.out.println(sum);
}
}
很简单:
public class TotalPoints {
public static void main(String[] args) {
String[] games = {"1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"};
int result = points(games);
}
public static int points(String[] games) {
//dowhat ever you want and return an int value
}
}
你可以写类似的东西
public class TotalPoints {
public static void main(String[] args) {
int sum = points(args);
System.out.println(sum);
}
public static int points(String[] games) {
int sum = 0;
int matches = 10;
int x = 0;
int y = 0;
for (int i = 0; i < games.length; i++) {
String[] pieces = games[i].split(":");
x = Integer.parseInt(pieces[0]);
y = Integer.parseInt(pieces[1]);
}
for (int j = 0; j < matches; j++) {
if (x > y) {
sum = sum + 3;
} else if (x == y) {
sum = sum + 1;
}
}
return sum;
}
}
当你运行这个类时,从命令行传递参数,比如java TotalPoints "1:0" "2:0" "3:0" "4:0" "2:1" "3:1" "4:1" "3:2" "4:2" "4:3"
我向你推荐这个
public class TotalPoints {
public static void main(String[] args) {
String[] games = {"1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"};
int sum = points(games);
System.out.println(sum);
}
private static int points(String[] games) {
int sum = 0;
int matches = 10;
int x = 0;
int y = 0;
for (String game : games) {
String[] pieces = game.split(":");
x = Integer.parseInt(pieces[0]);
y = Integer.parseInt(pieces[1]);
}
for (int j = 0; j < matches; j++) {
if (x > y) {
sum = sum + 3;
}
else if (x == y) {
sum = sum + 1;
}
}
return sum;
}
}
我将for (int i = 0; i < games.length; i++)
替换for (int i = 0; i < games.length; i++)
for (String game : games)
这是浏览列表的一种更简单的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.