0

I am trying to find the largest values of these three variables (aCounter, bCounter, cCounter) that has been calculated. Java does not like how I am putting them into the string. 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 );

3 Answers 3

4

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:

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? 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? Since the type of largestInt is int, it would make sense to use int instead for the counters.

Sign up to request clarification or add additional context in comments.

2 Comments

It is double because I have divided the count by the total number of letters.
I see. In that case, I changed the type of largestOfAB to double in my post
0
String lines = aCounter +" "+ bCounter +" "+ cCounter;

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.