Help Calling Method From Another Class
Hello again!
Can anybody help me figure out how to call my getActivity method from my student class in my app class? I'm trying display how much a student does a certain activity, but my loop goes on forever and doesn't stop at 20.
Student class
Code :
public class student {
String firstName;
String lastName;
int age;
student(String informedFirst, String informedLast, int informedAge)
{
firstName=informedFirst;
lastName=informedLast;
age=informedAge;
}
String getName()
{
return firstName + " " +lastName;
}
String getInfo()
{
return firstName + " " +lastName+" "+age;
}
String getActivity()
{
int myNumber = (int) (Math.random() * 3);
String result = " ";
if(myNumber == 0)
result = "Reading";
if(myNumber == 1)
result = "Programming";
if(myNumber == 2)
result = "Surfing";
return result;
}
}
App class
Code :
public class App {
public static void main(String args[])
{
student st1=new student("Zack","Mills",20);
int countReading=0;
int countProgramming=0;
int countSurfing=0;
for(int i=0;i<20;i++)
{
double outcome =Math.random()*3;
if(outcome == 0)
countReading++;
else
if (outcome ==1)
countProgramming++;
else
if(outcome ==2)
countSurfing++;
String action=st1.getActivity();
}
System.out.println("Zack is"+st1.getActivity()+ countReading*100/20+"%");
}
}
Re: Help Calling Method From Another Class
Your program is correct. Its running and stopping after 20 times. The output is always 0 as you are matching a double value with integer value which will never be true.
So you change your code as follows:
if((int)outcome == 0)
countReading++;
else
if ((int)outcome ==1)
countProgramming++;
else
if((int)outcome ==2)
countSurfing++;
I am here typecasting the outcome from double to integer. Click on thanks link
Re: Help Calling Method From Another Class
Thanks a bunch. I had not realized I was missing the int. It works perfectly now!