Reputation: 11
I cant seem to get the value of the second method please teach me how I'm still a beginner at this. Do I have to use a different variable? And if so how do I assign the return value of that method to the said variable?
import java.util.Scanner ;
class JavaChip
{
static Scanner s = new Scanner(System.in) ;
static double val ;
public static void main( String[] args )
{
displayLine () ;
System.out.print ("Enter number of cups of Mocha JavaChip: ");
val = getMocha( s.nextDouble() ) ;
System.out.print ("The grams of mocha is: " + val ) ;
System.out.print ("\nThe grams of sugar is: " + val ) ;
displayLine () ;
}
static double getMocha ( double c )
{
return ( 1.215 * c ) ;
}
static double getSugar (double c)
{
val = ( 0.15 * c ) ;
return val ;
}
static void displayLine()
{
System.out.println("\n\n[][][][][][][][][][][][][][][][][][][]") ;
System.out.println("[][][][][][][][][][][][][][][][][][][]") ;
}
}
Upvotes: 0
Views: 18776
Reputation: 18489
Your code is 100% correct.Just you are not calling that getSugar(double value) method. Just do the same as you did for getMocha(double value).Then you can get the return value.
Upvotes: 1
Reputation: 24063
Actually you should saparate your project into two files:
1. File that will include the main function and helper functions of display like displayLine.
2. File that wil represent the business of your project (JavaChip?).
Example:
Program.java:
class Program
{
public static void main( String[] args )
{
displayLine () ;
System.out.print ("Enter number of cups of Mocha JavaChip: ");
Scanner s = new Scanner(System.in) ;
JavaChip jc=new JavaChip();
double val = jc.getMocha( s.nextDouble()) ;
System.out.print ("The grams of mocha is: " + val ) ;
val = jc.getSugar( s.nextDouble());
System.out.print ("\nThe grams of sugar is: " + val ) ;
displayLine () ;
}
static void displayLine()
{
System.out.println("\n\n[][][][][][][][][][][][][][][][][][][]") ;
System.out.println("[][][][][][][][][][][][][][][][][][][]") ;
}
}
JavaChip.java:
class JavaChip
{
public JavaChip()
{
}
public double getMocha ( double c )
{
return ( 1.215 * c ) ;
}
public double getSugar (double c)
{
val = ( 0.15 * c ) ;
return val ;
}
}
Upvotes: 1
Reputation: 533492
If you want to use the value of a method you have to call it.
val = getSugar(num);
Using static fields to pass arguments or return values is bad practice. This is likely to cause confusion and be a cause of subtle multi-threaded bugs. Its also more complex than just returning the value like you do with getMocha()
Upvotes: 5