简体   繁体   中英

What am i doing wrong with arrays in methods?

I am unsure of what i have done wrong. I am using Java, and my console is saying that it cant find the symbol getBattingAverage.batters(i). batters is an array of 15 names, at bats, and hits ex: Anthony Rizzo 54 16.

public double getBattingAverage()
   {
   if(atBats > 0)
   return (double) hits / (double) atBats;
  else
   return 0.0; 
   }

public double getHighestBattingAverage()
   {
      for( i = 0; i < batters.length; i++)
         {
            j = getBattingAverage.batters(i);
            if ( maxERA < j)
               maxERA = j;

   }

The syntax here:

 j = getBattingAverage.batters(i);

Should either be - a method call on an array element:

j = batters[i].getBattingAverage();

or - a method call on a list element.

j = batters.get(i).getBattingAverage();

or - a method call using an array element

j = getBattingAverage(batters[i]);

for example.

But honestly, the real answer here: don't go for trial and error regarding syntax. Study books/tutorials, learn how those things are supposed to work.

This is not valid Java - will not compile. It's not obvious from your code what you intend.

I see you defined a function getBattingAverage(). That's OK assuming that you defined atBats and hits somewhere else. Probably as instance fields in the containing object. Please use curly braces with if statements.

In your for loop in getHighestBattingAverage you treat batters as though it's an array. Then you say getBattingAverage.batters(i) as though getBattingAverage is an object of a class which has a batters() method. Where did j come from? Where did maxERA come from?

Java has excellent documentation. Here is the section on Arrays , Language Basics , and the Tutorials Home , and the API Reference . This is how I taught myself Java.

You may find it helpful to use an IDE like IntelliJ because it tells you what the errors are as you're typing and gives you hints for writing better code. Good luck learning Java!

All that said, the ideal StackOverflow question has one issue. This looks like it's your first Java program and it looks like a good effort. But StackOverflow is for more specific questions. Questions like "nothing works and here's an incomplete excerpt that I need explained " will be closed as too broad. In fact, I'll probably vote to close this as being not well enough formed, or really not having a single specific issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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