简体   繁体   中英

java basic array question

List[K] = new Station(Location, Temp, Name);

In one method I enter in the values for Location and Name. In a later method I would like to loop through each Location and assign a unique Temp.

       public void Post() 
{
     double Temp = 0;
     int K;
     for(K = 0; K < Count ; K++)
     System.out.print(" " + List[K].GetLocation() + ": ");
     System.out.println("Enter Temperature");
     Temp = Input.nextDouble();

}

This simply dumps out all the locations and after that it prompts for a temperature and accepts it. But the temperature is not even assigned to the last value in the array.

Put curly braces around your for-loop body.

public void Post() 
{
     double Temp = 0;
     int K;
     for(K = 0; K < Count ; K++) {
         System.out.print(" " + List[K].GetLocation() + ": ");
         System.out.println("Enter Temperature");
         Temp = Input.nextDouble();
     }
}

BTW, you should read the standard Java conventions .

Is this what you would like to do? Print out each location in the list and request the temperate from the user?

  public void Post() { double Temp = 0; int K; for(K = 0; K < Count ; K++) { System.out.print(" " + List[K].GetLocation() + ": "); System.out.println("Enter Temperature"); Temp = Input.nextDouble(); } } 

Why is Temp initialized in the first line? Why is there an assignement in the last line? It has no effect.

Why do you declare K outside of the loop? The Codeconventions asks for lowercase letters for attributes, parameters, variables and methods.

  list[k] = new Station (location, temp, name);
// 

public void post () 
{
     for (int k = 0; k < count; k++)
         System.out.print (" " + list[k].getLocation () + ": ");
     System.out.println ("Enter Temperature");
     double Temp = Input.nextDouble ();
}

In one method I enter in the values for Location and Name. In a later method I would like to loop through each Location and assign a unique Temp.

Well - you loop through stations, not locations, do you?

But the temperature is not even assigned to the last value in the array.

Which Array? The Array called List? You never assign temp to something, do you?

Do you have a setter in Station? Is it a writable attribute?

list[count-1].setTemp (temp); // or 
list[count-1].temp = temp; 

might help.

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