简体   繁体   English

Java:获取变量的最大值

[英]Java: Get maximum value of variables

I am trying to find the largest values of these three variables (aCounter, bCounter, cCounter) that has been calculated. 我试图找到已计算的这三个变量(aCounter,bCounter,cCounter)的最大值。 Java does not like how I am putting them into the string. Java不喜欢我将它们放入字符串的方式。 Thanks in advance guys! 在此先感谢大家!

   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 );

It's strange what you're doing: 您正在做的事情很奇怪:

  • Concatenate three numbers into a string 将三个数字连接成一个字符串
  • Split the string 分割字符串
  • Parse numbers out of the split result 从拆分结果中解析数字
  • Find the max.... 找到最大的...。

You could find the max value directly from the numbers: 您可以直接从数字中找到最大值:

int largestInt = Math.max(aCounter, Math.max(bCounter, cCounter));

Or if you don't want to use Math.max , then: 或者,如果您不想使用Math.max ,则:

double largestOfAB = aCounter > bCounter ? aCounter : bCounter;
int largestInt = largestOfAB > cCounter ? largestOfAB : cCounter;

Or if you want a loop solution: 或者,如果您需要循环解决方案:

double largest = aCounter;
for (double number : new double[]{ bCounter, cCounter})
{
    if (number > largestInt)
    {
        largest = number;
    }
}
int largestInt = (int) double;

Btw it begs the question, why are aCounter , bCounter and cCounter of type double ? aCounter一个问题,为什么aCounterbCountercCounter类型为double The count of letters suggests integer numbers. 字母数表示整数。 Unless it's average counts. 除非是平均数。 But then if it's average counts then why would you want an int valued largestInt at the end? 但是,如果它是平均计数,那么为什么还要在末尾使用值largestIntint Since the type of largestInt is int , it would make sense to use int instead for the counters. 由于largestInt的类型是int ,因此将int用作计数器是有意义的。

String lines = aCounter +" "+ bCounter +" "+ cCounter;

You should replace 你应该更换

String lines = aCounter + bCounter + cCounter;

to

String lines = aCounter + " " + bCounter + " " + cCounter;

If you REALLY want to use this way, otherwise 如果您真的要使用这种方式,否则

int largest=0;
if(aCounter>bCounter) {
 if(aCounter>cCounter) {
  largest=aCounter;
 } else {
  largest=cCounter;
 }
} else {
 if(bCounter>cCounter) {
  largest=bCounter;
 } else {
  largest=cCounter;
 }
}

or 要么

int largest=Integer.MIN_VALUE;
if(aCounter>largest) largest=aCounter;
if(bCounter>largest) largest=bCounter;
if(cCounter>largest) largest=cCounter;

would be a better way, skipping the use of Strings. 跳过字符串的使用将是更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM