[solved]- need help prog skipping method
Hi this is the question i was given
Write a menu driven program that allows the user to enter a value for x and provides three options:
i. Find the square of the number
ii. Find the cube of the number
iii. The third option allows the user to quit.
Make use of methods in your program for each option above. Note the methods to find the square and cube of the number should receive one parameter of type double and return the answer.
And here is my attemt. It compiles but it always cubes the number entered even if i choose option a to square. I've also tweaked the code to valadiate that the correct letters have been entered.
If you could highlight where im going wrong in red please.Any help would be greately appricated.
Code :
class WS1Q3
{
public static void main(String[] args)
{
double x, result;
char ans;
System.out.println("enter a number");
x=Keyboard.readDouble();
System.out.println("press 'A' to square the number, 'B' to cube or 'C' to quit");
ans=Keyboard.readChar();
if(ans!='A' && ans !='B' && ans!='C' && ans!='a' && ans !='b' && ans!='c')
{
do // valadating correct letters entered
{
System.out.print("Error enter either A,B or C");
ans=Keyboard.readChar();
}while(ans!='A' && ans!='B' && ans!='C' && ans!='a' && ans !='b' && ans!='c');
}
// use of if statment to use requested method
if(ans == 'A' || ans == 'a')
{
result=square(x);
}
if(ans =='B' || ans =='b');
{
result=cube(x);
}
if(ans == 'C' || ans =='c')
{
System.out.println("Goodbye");
}
System.out.println("the result is "+result);
System.out.println("Goodbye");
}//close main
static double square(double x)
{
double result;
result = x*x;
return result;
}//close method square
static double cube(double x)
{
double result;
result= x*x*x*x;
return result;
}//close method cube
}//close class
Re: need help prog skipping method
Hi, Please tell what is Keyboard here. I am unable to resolve it. Is it some other class or an object
Re: need help prog skipping method
I debugged your program and found following errors.
1.You have used semicolon in if second if statement
if(ans =='B' || ans =='b');
Remove this semicolon and write statement as
if(ans =='B' || ans =='b')
2. In cube you are multiplying the number 4 times. It should be 3 times like as
result= x*x*x;
3. Initialize your result to 0. other wise there will be an error.
Enjoy buddy and say click on thanks link..
Re: need help prog skipping method
Cheers jassi guessed you figured out that it's a class file that reads the input from the user.
Q. is there any benefits from writting the keyboard class file a different way i.e read.console() - i think i seen this 1
Re: need help prog skipping method
I think its not. You can use Scanner class to get data from Keyboard. I have seen many apps where in Scanner is used.