[英]Java: Get maximum value of variables
我试图找到已计算的这三个变量(aCounter,bCounter,cCounter)的最大值。 Java不喜欢我将它们放入字符串的方式。 在此先感谢大家!
double aCounter=0;
double bCounter=0;
double cCounter=0;
{ code to count occurrences of each character in text file }
String lines = aCounter + bCounter + cCounter;
String [] array = lines.split (" "); //splits with a space
int largestInt = Integer.MIN_VALUE;
for (String numberString : array )
{
int number = Integer.parseInt(numberString);
if (number > largestInt)
{
largestInt = number;
}
}
bw.write ( largestInt );
您正在做的事情很奇怪:
您可以直接从数字中找到最大值:
int largestInt = Math.max(aCounter, Math.max(bCounter, cCounter));
或者,如果您不想使用Math.max
,则:
double largestOfAB = aCounter > bCounter ? aCounter : bCounter;
int largestInt = largestOfAB > cCounter ? largestOfAB : cCounter;
或者,如果您需要循环解决方案:
double largest = aCounter;
for (double number : new double[]{ bCounter, cCounter})
{
if (number > largestInt)
{
largest = number;
}
}
int largestInt = (int) double;
aCounter
一个问题,为什么aCounter
, bCounter
和cCounter
类型为double
? 字母数表示整数。 除非是平均数。 但是,如果它是平均计数,那么为什么还要在末尾使用值largestInt
的int
? 由于largestInt
的类型是int
,因此将int
用作计数器是有意义的。
String lines = aCounter +" "+ bCounter +" "+ cCounter;
你应该更换
String lines = aCounter + bCounter + cCounter;
至
String lines = aCounter + " " + bCounter + " " + cCounter;
如果您真的要使用这种方式,否则
int largest=0;
if(aCounter>bCounter) {
if(aCounter>cCounter) {
largest=aCounter;
} else {
largest=cCounter;
}
} else {
if(bCounter>cCounter) {
largest=bCounter;
} else {
largest=cCounter;
}
}
要么
int largest=Integer.MIN_VALUE;
if(aCounter>largest) largest=aCounter;
if(bCounter>largest) largest=bCounter;
if(cCounter>largest) largest=cCounter;
跳过字符串的使用将是更好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.