I'm quite new to java. I have studied my code for a long time and I just can't find a good way to declare the args array in a simple string I can count _length();
我对java很新。我已经研究了我的代码很长一段时间,我找不到一个很好的方法来在一个简单的字符串中声明args数组我可以计算_length();
I am getting the args array by doing the following in cmd: java Sentence this is a good day to die
. The output is the way i want it atm, but, how do I efficiently count an args array for characters? My way of declaring every single args[0], args[1]
, etc doesn't feel right.
我通过在cmd中执行以下操作来获取args数组:java Sentence这是一个美好的一天。输出是我想要它的方式,但是,我如何有效地计算字符的args数组?我宣告每一个args [0],args [1]等的方法感觉不对。
Right now this is my code:
现在这是我的代码:
public class Sentence {
public static void main(String[] args) {
String s = args[0];
String t = args[1];
String a = args[2];
String r = args[3];
String l = args[4];
int sum = s.length()+t.length()+a.length()+r.length()+l.length();
System.out.print("You wrote: ");
for (int j=0; j < args.length; j++){
System.out.print(" "+args[j]);
}
if (args.length > 0) {
System.out.println("\nNumber of Words:\t"+args.length);
System.out.println("Number of characters:\t"+sum);
}
}
}
3 个解决方案
#1
4
args
is an array. You should iterate over it :
args是一个数组。你应该迭代它:
int sum=0;
for (String s : args) {
sum+=s.length();
}
#2
3
You can simply do.
你可以干脆做。
public static void main(String[] args) {
int count =0;
for (String string : args) {
count += string.length()
}
System.out.println(count);
}
Loop on you args and add the each strings length to count
variable.
循环你args并将每个字符串长度添加到count变量。
#3
0
When you use
当你使用
String s = args[0];
String t = args[1];
String a = args[2];
You can't predetermine the length of the sentence. Java handles that argument array for you. What you should do is iterate through that array and get the length of each argument length and added them together. So code would looks like
你不能预先确定句子的长度。 Java为您处理该参数数组。你应该做的是迭代该数组并获得每个参数长度的长度并将它们加在一起。所以代码看起来像
int sum = 0
for(String arg : args)
sum += arg.length();
#1
4
args
is an array. You should iterate over it :
args是一个数组。你应该迭代它:
int sum=0;
for (String s : args) {
sum+=s.length();
}
#2
3
You can simply do.
你可以干脆做。
public static void main(String[] args) {
int count =0;
for (String string : args) {
count += string.length()
}
System.out.println(count);
}
Loop on you args and add the each strings length to count
variable.
循环你args并将每个字符串长度添加到count变量。
#3
0
When you use
当你使用
String s = args[0];
String t = args[1];
String a = args[2];
You can't predetermine the length of the sentence. Java handles that argument array for you. What you should do is iterate through that array and get the length of each argument length and added them together. So code would looks like
你不能预先确定句子的长度。 Java为您处理该参数数组。你应该做的是迭代该数组并获得每个参数长度的长度并将它们加在一起。所以代码看起来像
int sum = 0
for(String arg : args)
sum += arg.length();