Monday, June 17, 2013

Java Program Constants, Variable Declarations, Arithmetic Expressions, Assignments, Input, and Format Output.



Programming Project for Eclipse

Assignment
A convenience store sells T-shirt, potato chips, and Coke. The list prices are: $18.95 for T-shirt, $1.79 for a bag of potato chips, and $2.99 for a 12-pack Coke ($1.20 deposit as well). All merchandise except Coke is on sale with 15% off the list price. T-shirt is also charged a 6% Michigan sales tax. A customer shops at the store to buy these items. Write a Java program to simulate the shopping process — interact with the custom and prints a receipt.





Code





import java.util.Scanner;

public class a {

/**
 * 
 */
 
public static void main(String[] args) {
 //TODO Audto-generated method stub
 
 
Scanner keyboard = new Scanner(System.in);
 
double shirts = 18.95;
int numOfShirts;
int numOfChips;
int numOfCoke;
double cokeTotal;
double chips = 1.79;
double coke = 2.99;
double subTotal;
double deposit = 1.20;
double preTotal;  
double MItax = 0.06; 
double totalTax; 
double total; 
double payment; 
String name;

//Prompt for the name
System.out.print("What's your name?");
name = keyboard.nextLine();
System.out.println("Welcome to Denny's Market" + name + "! We have the following items for sale:\n");
System.out.println("T-shirt $ " + shirts + " 15% off");
System.out.println("Chips $ " + chips + " 15% off");
System.out.println("Coke $ " + coke + "\n");


//Prompt for number of the shirts 
System.out.println("How many T-shirts do you want?");
numOfShirts = keyboard.nextInt(); 
System.out.println("How many bags of chips would you like?");
numOfChips = keyboard.nextInt();
System.out.println("What about 12-pack Coke?");
numOfCoke = keyboard.nextInt();

//Calculations for the program
cokeTotal = (numOfCoke * deposit) + (numOfCoke * coke);
subTotal = (((shirts * numOfShirts) + (chips * numOfChips) + (coke * numOfCoke) + (deposit * numOfCoke)));
total = (numOfShirts * shirts) *.85 + (numOfChips * chips) *.85 + cokeTotal;
preTotal = (numOfShirts *shirts) + (numOfChips * chips) + cokeTotal;
totalTax = total * MItax; 
total = total + totalTax;

System.out.println("Your total is: $" + total);
System.out.println("Please enter your payment:");
payment = keyboard.nextDouble(); 
System.out.println("\n");

System.out.println(name + ", here is your receipt:");
System.out.println("");
System.out.println("\tItem \tUnit Price \tHow Many \tCost" + "\t");
System.out.println("-----------------------------------------------------------");

System.out.println("\tT-shirt" + "\t" + shirts + "\t" + numOfShirts + "\t" + (shirts * numOfShirts));
System.out.println("\tChips" + "\t" + chips + "\t" + numOfChips + "\t" + (chips * numOfChips)); 
System.out.println("\tCoke" + "\t" + coke + "\t" + numOfCoke + "\t" + (coke * numOfCoke));
System.out.println("\tDeposit" + "\t\t" + "\t" +  + (deposit * numOfCoke));
System.out.println("\n");

System.out.println("\tSubtotal" + "\t\t" + + subTotal);
System.out.println("\tDiscount" + "\t\t" + "-" + (preTotal-total));
System.out.println("\tTax" + "\t\t" + "\t" + + totalTax);
System.out.println("\t" + "\t\t" + "\t" + "---------\n");
System.out.println("\tTotal" + "\t\t" + "\t" + + total + "\n");

//Payment
System.out.println("\tPayment" + "\t\t" + "\t" +  + payment);

//Doing the change
System.out.println("\tYourChange"+ "\t\t" + + ((payment - total)) + "\n");
System.out.println("Than you. Come Again!");
}
}


Java Program Sentinel Control Loop



Java Program Sentinel Control Loop



Use in Program Eclipse


import java.util.Scanner;
public class SentinelControlLoop {

 /**
  * 
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  Scanner myInput = new Scanner(System.in);
  
  
  //Declare Variables
  int num, sum = 0, max, min, count =0;
  double average = 0.0;
  final int Sentinel = -9999;
  
  
  //Priming Stage
  System.out.print("Enter an integer value, or -9999 to quit: ");
  num = myInput.nextInt();
  
  //intitalize max and min
  max = min = num;
  
  
  
  //WHILE Loop
  while (num != Sentinel) {
   //body of loop
   //Update Sum
   sum = sum + num; //sum +=
   System.out.println("Sum is now "+ sum);
   
   if (num > max)
    max = num;
   if (num < min)
    min = num;
   
   //increment count of data items read
   count++; //Same as count = count + 1;
   System.out.print("num = " + num + " Count = " + count );
   System.out.print(" Enter an integer value, or -9999 to quit: ");
   num = myInput.nextInt();
   
   
  }
  if (count != 0) {
   average = (double)sum / count;
   System.out.println("Average is " + average);
   System.out.println (" max = "+ max + ", min " + min);
  }
  else 
   System.out.println("Cant average 0 items ");
  
 }

}





-->

Java Program Methods



Java Program for Eclipse



Lab Objectives: To develop ability to write void and value returning methods and to call them
Introduction: Methods are commonly used to break a problem down into small manageable pieces. A large task can be broken down into smaller tasks (methods) that contain the details of how to complete that small task. The larger problem is then solved by implementing the smaller tasks (calling the methods) in the correct order.
This also allows for efficiencies, since the method can be called as many times as needed without rewriting the code each time.
Task #1 void Methods
1.   Type the code (Geometry.java) shown in at the end of this handout. This program will compile, but when you run it, it doesn’t appear to do anything except wait. That is because it is waiting for user input, but the user doesn’t have the menu to choose from yet. We will need to create this.
2.   Above the main method, but in the Geometry class, create a static method called printMenu that has no parameter list and does not return a value. It will simply print out instructions for the user with a menu of options for the user to choose from. The menu should appear to the user as:
This is a geometry calculator
Choose what you would like to calculate
1. Find the area of a circle
2. Find the area of a rectangle
3. Find the area of a triangle
4. Find the circumference of a circle
5. Find the perimeter of a rectangle
6. Find the perimeter of a triangle
Enter the number of your choice:
3.   Add a line in the main method that calls the printMenu method as indicated by the comments.
4.   Compile, debug, and run.  You should be able to choose any option, but you will always get 0 for the answer. We will fix this in the next task.
Task #2 Value-Returning Methods
1.   Write a static method called circleArea that takes in the radius of the circle and returns the area using the formula A = Ï€ r 2 .
2.   Write a static method called rectangleArea that takes in the length and width of
the rectangle and returns the area using the formula A = lw.
3.   Write a static method called triangleArea that takes in the base and height of the triangle and returns the area using the formula A = ½bh.
4.   Write a static method called circleCircumference that takes in the radius of the circle and returns the circumference using the formula C = 2Ï€r.
5.   Write a static method called rectanglePerimeter that takes in the length and the width of the rectangle and returns the perimeter of the rectangle using the formula P = 2l +2w.
6.   Write a static method called trianglePerimeter that takes in the lengths of the three sides of the triangle and returns the perimeter of the triangle which is calculated by adding up the three sides.
Task #3 Calling Methods
1.   Add lines in the main method in the Geometry class which will call these methods. The comments indicate where to place the method calls.
2.   Compile, debug, and run.  Test out the program using your sample data.





import java.util.Scanner;
// Demonstration of static methods
public class PutYourClassHere
 {
 public static void main (String [] args)
  {
  int choice; //the user's choice
  double value = 0; //the value returned from the method
  char letter;  //the Y or N from the user's decision to exit 
  double radius; //the radius of the circle
  double length; //the length of the rectangle 
  double width,height;  //the width and height of the rectangle 
  double base;  //the base of the triangle 
  double side1,side2,side3;  // sides of the triangle

//create a scanner object to read from the keyboard
  Scanner keyboard = new Scanner (System.in);

//do loop was chose to allow the menu to be displayed first do
  do
  {
   //call the printMenu method here
   printMenu();
   choice = keyboard.nextInt();

  switch (choice)
  {
   case 1:
    System.out.print("Enter the radius of the circle:  ");
    radius = keyboard.nextDouble();
    value = circleArea(radius);
     //call the circleArea method and store the result in the value 
    System.out.println("The area of the circle is " + value);
    break;
   case 2:
    System.out.print("Enter the length of the rectangle:  "); 
    length = keyboard.nextDouble();
    System.out.print("Enter the width of the rectangle:  ");
    width = keyboard.nextDouble();
    value = rectangleArea(length,width);
    //call the rectangleArea method and store the result in the value 
    System.out.println("The area of the rectangle is " + value); 
    break;
   case 3:
    System.out.print("Enter the height of the triangle:  "); 
    height = keyboard.nextDouble(); 
    System.out.print("Enter the base of the triangle:  "); 
    base = keyboard.nextDouble();
    value = triangleArea(height,base);
    //call the triangleArea method and store the result in the value 
    System.out.println("The area of the triangle is " + value); 
    break;
   case 4:
    System.out.print("Enter the radius of the circle:  ");
    radius = keyboard.nextDouble();
    value = circleCircumference(radius);
    //call the circumference method and store the result in the value 
    System.out.println("The circumference of the circle is " + value); 
    break;
   case 5:
    System.out.print("Enter the length of the rectangle:  "); 
    length = keyboard.nextDouble(); 
    System.out.print("Enter the width of the rectangle:  "); 
    width = keyboard.nextDouble();
    value = rectanglePerimeter(length,width);
    //call the perimeter method and store the result in the value 
    System.out.println("The perimeter of the rectangle is " + value); 
    break;
   case 6:
    System.out.print("Enter the length of side 1 of the triangle:  ");
    side1 = keyboard.nextDouble();
    System.out.print("Enter the length of side 2 of the triangle:  ");
    side2 = keyboard.nextDouble();
    System.out.print("Enter the length of side 3 of the triangle:  ");
    side3 = keyboard.nextDouble();
    value = trianglePerimeter(side1,side2,side3);
    //call the perimeter method and store the result in the value 
    System.out.println("The perimeter of the triangle is " + value); 
    break;
   default:
  System.out.println("You did not enter a valid choice.");
     }//end of switch statement
//consumes the new line character after the number 
  keyboard.nextLine();

  System.out.println("Do you want to exit the program (Y/N)?:  "); 
  String answer = keyboard.nextLine();
  letter = answer.charAt(0); //select first character of response

  }while (letter != 'Y' && letter != 'y'); //end of do-while loop

 }//end of main

//insert your method definitions here
 public static void printMenu() {
  System.out.println("This is a geometry calculator ");
  System.out.println("Choose what you would like to calculate!");
  System.out.println("1. Find the area of a cirlce ");
  System.out.println("2. Find the area of a rectangle ");
  System.out.println("3. Find the area of a triangle ");
  System.out.println("4. Find the circumference of a cirle ");
  System.out.println("5. Find the perimeter of a rectangle ");
  System.out.println("6. Find the perimeter of a triangle");
  System.out.print("Enter the number of your choice: ");
 }
 public static double circleArea(double r) {
  return Math.PI * r * r;
 }
 public static double rectangleArea(double length, double width) {
  return length * width;
 }
 public static double triangleArea(double height, double base) {
  return .5 * height * base;
 }
 public static double circleCircumference(double r) {
  return 2 * Math.PI * r;
 }
 public static double rectanglePerimeter(double length,double width) {
  return 2 * length + 2 * width;
 }
 public static double trianglePerimeter(double side1,double side2, double side3) {
  return side1 + side2 + side3;
 }


}//end of class

Java Program Methods/Arrays Exam Scores Average, Max and Min



Java Program for Arrays. Average, Random Shuffle, Max and Min Arrays for Exam Scores

For use in Eclipse.



import java.util.Scanner;
public class Put Your Class here {

 /**
  * 
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  double[] exam1 = new double[10];
  double average;
  double max, min;
  

  fillArray(exam1);
  printArray(exam1);
  average = getArrayAverage (exam1);
  System.out.printf(" Average Exam 1 Score is %6.2f \n", average);
  max = getMax(exam1);
  min = getMin(exam1);
  randomShuffle(exam1);
  printArray(exam1);
 
  selectionSort(exam1);
  printArray(exam1);
  
  
  
 }//End of main
 public static void fillArray( double[] list) {
  Scanner myIn = new Scanner(System.in);
  for (int i=0; i <list.length; i++){
   System.out.print("Enter a number: ");
   list[i] = myIn.nextDouble();
  }//end of for loop
 }//end of the fill array loop

 public static void printArray(double[] list) {
  System.out.println(" \t Index \t Value \n");//print header
  System.out.println("=======================");
  for (int i=0; i <list.length; i++){
   System.out.println("\t" + i + "\t" + list[i]);
  }//end of for loop
 }//end of print array method
 
 public static void randomShuffle(double[] list) {
  int j; 
  double temp;
  for (int i= 0; i <list.length; i++) {
   j = (int)(Math.random() * 5);
 
  j= (int) (Math.random() * list.length);
  temp = list[i];
  list[i] = list[j];
  list[j] = temp;
 }//end of for
}// end of random shuffle
 
 public static void selectionSort(double[] list) {
  double currentMin;
  int currentMinIndex;
  
  for (int i = 0; i < list.length - 1; i++) {
   currentMin = list[i];
   currentMinIndex = i;
   
   for (int j= i + 1; j < list.length; j++){
    if (list[j] < currentMin) {
     currentMin = list[j]; currentMinIndex = j;
    }//end if
   }//end inner loop
   if (currentMinIndex != i) {
    list[currentMinIndex] = list[i];
    list[i] =currentMin;
   }//end if
  }// end outer loop
 }//end selection sort
 
 public static double  getArrayAverage(double[] list) {
  double avg=0.0, total=0.0;
  
  for (int i=0; i <list.length; i++){
   total = total + list[i];
  }//end of for loop
  if (list.length > 0) avg = total / list.length;
  return avg;
 }//end of the get array average method
 
 public static double getMax(double[] list) {
  double m = Double.MAX_VALUE;
  for (int i =0; i < list.length; i++){
   if (list[i] > m) m = list[i];
  }
  return m;
 }
 public static double getMin(double[] list) {
  double n = Double.MAX_VALUE;
  for (int i =0; i < list.length; i++){
   if (list[i] < n) n = list[i];
  }
  return n;
 }

 
}//End


MyProgrammingLab Solutions Part 2


Here is some help for MyProgrammingLab
Use a finder (Command-f on Macs) and type in your problem to find your question faster.



Rearrange the following code so that it forms a correct program that prints out the letter Q:


public class Q
{
public static void main(String[] a)
{
System.out.println("Q");
}
}


Given an integer variable  count , write a statement that displays the value of  count on the screen.

 Do not display anything else on the screen -- just the value of  count .

System.out.print (count) ;



 Given the variables  fullAdmissionPrice and  discountAmount (already declared and assigned values), write an expression corresponding to the price of a discount admission.

fullAdmissionPrice - discountAmount



 The dimensions (width and length) of room1 have been read into two variables:  width1 and  length1 . The dimensions of room2 have been read into two other variables:  width2 and  length2 . Write a single expression whose value is the total area of the two rooms.

(width1*length1)+(width2*length2)



 Assume that  word is a String variable. Write a statement to display the message "Today's Word-Of-The-Day is: " followed by the value of  word on a line by itself on standard output.

System.out.println("Today's Word-Of-The-Day is: " + word);

Write an expression that concatenates the String variable  suffix onto the end of the String variable  prefix . 

prefix+suffix

 Declare a variable  hasPassedTest , and initialize it to true. 

boolean hasPassedTest = true;


Given an  int variable  grossPay , write an expression that evaluates to true if and only if the value of  grossPay is less than  10,000 . 

grossPay < 10000

 Write an expression that evaluates to true if the integer variable  x contains an even value, and false if it contains an odd value.

x % 2 == 0


 Assume that the variables  gpa ,  deansList and  studentName , have been declared and initialized. Write a statement that adds 1 to  deansList and prints  studentName to standard out if  gpa exceeds 3.5. 

if (gpa > 3.5){
deansList += 1;
System.out.print(studentName);
}


 Write an if/else statement that compares the variable  age with  65 , adds  1 to the variable  seniorCitizens if  age is greater than or equal to  65 , and adds  1 to the variable  nonSeniors otherwise.

if (age >= 65)
seniorCitizens += 1;
else
nonSeniors += 1;

Write an if/else statement that compares the value of the variables  soldYesterday and  soldToday , and based upon that comparison assigns  salesTrend the value  -1 or  1 .

 -1 represents the case where  soldYesterday is greater than  soldToday ; 1 represents the case where  soldYesterday is not greater than  soldToday . 


if (soldYesterday > soldToday)
salesTrend = -1;
else
salesTrend = 1;



 Write an if/else statement that adds  1 to the variable  minors if the variable  age is less than  18 , adds  1 to the variable  adults if  age is  18 through  64 and adds  1 to the variable  seniors if  age is  65 or older. 

if (age < 18)
minors ++ ;
else if(age >= 18 && age <= 64)
adults ++;
else if (age >= 65)
seniors ++;

Given an  int variable  k that has already been declared, use a  while loop to print a single line consisting of 88 asterisks. Use no variables other than  k . 

k= 88;
while(k>0)
{
System.out.print("*");
k--;
}


Given an  int variable  n that has already been declared and initialized to a positive value, use a  while loop to print a single line consisting of  n asterisks. Use no variables other than  n . 

int k = 0 ;
while(k<=(n-1))
{
System.out.printf("*") ;
k+=1 ;
}


 Given  int variables  k and  total that have already been declared, use a  while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in  total . Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into  total . Use no variables other than  k and  total . 

k = 1 ;
total = 0 ;
while ( k <= 50 )
{
total = total + ( k * k ) ;
k = k + 1 ;
}


Given an int variable n that has already been declared, write some code that repeatedly reads a value into n until at last a number between 1 and 10 (inclusive) has been entered.

ASSUME the availability of a variable,  stdin , that references a  Scanner object associated with standard input.

do {
n = stdin.nextInt();
}
while (n>10 || n < 1);


Write a loop that reads positive integers from standard input, printing out those values that are even, each followed by a space, and that terminates when it reads an integer that is not positive. Declare any variables that are needed.

ASSUME the availability of a variable,  stdin , that references a  Scanner object associated with standard input.

int x = stdin.nextInt();
while(x>0)
if(x % 2 == 0)
{
System.out.print(x+" ");
x = stdin.nextInt();
}
else {
x = stdin.nextInt();
}


 Consider this data sequence: "3 11 5 5 5 2 4 6 6 7 3 -8". Any value that is the same as the immediately preceding value is considered a CONSECUTIVE DUPLICATE. In this example, there are three such consecutive duplicates: the 2nd and 3rd 5s and the second 6. Note that the last 3 is not a consecutive duplicate because it was preceded by a 7. Write some code that uses a loop to read such a sequence of non-negative integers, terminated by a negative number. When the code finishes executing, the number of consecutive duplicates encountered is printed. In this case,3 would be printed. 

int n, prev, consecdups=0;prev=stdin.nextInt();n=stdin.nextInt();while (n>=0) { if (n==prev) consecdups++; prev = n; n=stdin.nextInt();}System.out.println(consecdups);

Given an  int variable  n that has already been declared and initialized to a positive value, use a  do...while loop to print a single line consisting of  n asterisks. Use no variables other than  n . 

do
{
System.out.print("*");
n--; }
while (n>0);

Given  int variables  k and  total that have already been declared, use a  do...while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in  total . Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into  total . Use no variables other than  k and  total . 

for( k=1, total=0; k<=50; k++ ) total += k*k;

Given an  int variable  n that has been initialized to a positive value and, in addition,  int variables  k and  total that have already been declared, use a  do...while loop to compute the sum of the cubes of the first  n whole numbers, and store this value in  total . Use no variables other than  n ,  k , and  total . 

total = 0;
for(k = 1; k <=n; k++){
total += k * k * k;
}

Given  int variables  k and  total that have already been declared, use a  for loop to compute the sum of the squares of the first 50 counting numbers, and store this value in  total . Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into  total . Use no variables other than  k and  total . 

k = 1;
total = 0;
while (k<=50)
{
total += (k*k);
k++;
}



Assume the  int variables  i and  result have been declared but not initialized. Write a  for loop header, i.e. something of the form 
 for (  .   .   .   ) 
 for the following loop body: 
 result = result * i; 
 When the loop terminates,  result should hold the product of the odd numbers between  10 and  20 . 

for(i=11,result=1;i<20;i+=2)

Assume the int variables i ,lo , hi , and result have been declared and that lo and hi have been initialized. Assume further that result has been initialized to the value  0 . 

 Write a for loop that adds the integers from lo up through hi (inclusive), and stores the result in result .
 Your code should not change the values of lo and hi . Also, do not declare any additional variables -- use only i ,lo , hi , and result . 


for(i = lo; i <= hi; i++)
{
result += i;
}


 Given an  int variable  n that has already been declared and initialized to a positive value, and another  int variable  j that has already been declared, use a  for loop to print a single line consisting of  n asterisks. Thus if  n contains 5, five asterisks will be printed. Use no variables other than  n and  j .     

for(j=1;j<=n;++j)
{
System.out.print("*");
}

Write a  for loop  that prints the integers 0 through 39, separated by spaces. 

for(int i=0; i<40; i++)
{
System.out.print(i + " ");
}


Write a  for loop  that prints in ascending order all the positive multiples of 5 that are less than 175, separated by spaces. 


for (int i=5; i<175; i+=5) {
System.out.print(i+" ");
}



 Write a  for loop  that prints the integers 50 through 1, separated by spaces. Use no variables other than  count . 


for
( int count=50 ; count>=1; count--)
System.out.print( count + " ");



 Assume that the  int variables  i and  j have been declared, and that  n has been declared and initialized. 

 Using  for loops (you may need more than one), write code that will cause a triangle of asterisks of size  n to be output to the screen. 

for(i = 0; i < n; i++)
{
    for(j = 0; j <= i; j++)
        System.out.print("*");
    System.out.println();
}


If you can't find the answer you need on this post check my other MyProgrammingLab post for other questions and answers. If the answer still can't be found feel free to comment and let me know the question you need answered. 








MyProgrammingLab Solutions


My Programming Lab Questions and Answers



Declare a variable logfileName that is suitable for holding the name of a file.

String logfileName;

Suppose a reference variable of type  File called  myFile has already been declared. Create an object of type  File with the initial file name  input.dat and assign it to the reference variable  myFile .

myFile = new File ("input.dat");


Write a statement that declares a PrintWriter reference variable named output and initializes it to a reference to a newly created PrintWriter object associated with a file named "output.txt". (Do not concern yourself with any possible exceptions here-- assume they are handled elsewhere.)

PrintWriter output = new PrintWriter("output.txt");



 Given an initialized String variable outfile, write a statement that declares a PrintWriter reference variable named output and initializes it to a reference to a newly created PrintWriter object associated with a file whose name is given by outfile. (Do not concern yourself with any possible exceptions here-- assume they are handled elsewhere.)

PrintWriter output = new PrintWriter(outfile);



 Given a PrintWriter reference variable named output that references a PrintWriter object, write a statement that writes the string "Hello, World" to the file output streams to.

output. print("Hello, World");

 Given an initialized String variable message, and given a PrintWriter reference variable named output that references a PrintWriter object, write a statement that writes the string referenced by message to the file output streams to.

output.print(message);

 Given a String variable named line1 and given a Scanner reference variable stdin that has been assigned a reference to a Scanner object, read the next line from stdin and save it in line1. (Do not concern yourself with any possible exceptions here-- assume they are handled elsewhere.)

line1 = stdin.nextLine ();

 Given a String variable named line1 and given a Scanner reference variable fileInput that remains uninitialized, write a sequence of statements that read the first line of a file named "poem" and stores i in line1. (Do not concern yourself with any possible exceptions here-- assume they are handled elsewhere.)

Scanner fileInput= new Scanner(new File("poem"));

line1 =fileInput.nextLine();

Write the definition of a method  twice , which receives an integer parameter and returns an integer that is twice the value of the parameter. 

public int twice(int x){
return  x* 2;
}


Write the definition of a method  add , which receives two integer parameters and returns their sum. 


public int add( int x, int y ) { 
return x + y;
}


 Write the definition of a method  powerTo , which receives two parameters. The first is a  double and the second is an  int . The method returns a  double . 

 If the second parameter is negative, the method returns zero. Otherwise it returns the value of the first parameter raised to the power of the second parameter. 

public double powerTo (double number,int power)
{
double answer = 0 ;
while (power>=0)
{
answer = Math.pow(number,(double)power);
return answer;
}
return 0;
}



 Given that a method receives three parameters  a ,  b ,  c , of type double, write some code, to be included as part of the method, that checks to see if the value of a is 0; if it is, the code prints the message "no solution for a=0" and returns from the method.

if( a==0.0) 
System.out.println("no solution for a=0");
return;

Write the definition of a method  min that has two  int parameters and returns the smaller. 


public int min (int x,int y){
return Math.min(x,y);
}

Write the code for invoking a method named  sendSignal . There are no arguments for this method. 
Assume that  sendSignal is defined in the same class that calls it.

sendSignal();

 Write the code for invoking a method named  sendVariable . There is one int argument for this method. 
 Assume that an  int variable called  x has already been declared and initialized to some value. Use this variable's value as an argument in your method invocation. 
Assume that  sendVariable is defined in the same class that calls it.


sendVariable(x);

 Write the code for invoking a method named  sendTwo . There are two arguments for this method: a  double and an  int . Invoke the method with the  double value of  15.955 and the  int value of  133 . 
Assume that  sendTwo is defined in the same class that calls it.

sendTwo(15.955,133) ;

printLarger is a method that accepts two  int arguments and returns no value. 

 Two  int variables,  sales1 and  sales2 , have already been declared and initialized. 

 Write a statement that calls  printLarger , passing it  sales1 and  sales2 . 

Assume that  printLarger is defined in the same class that calls it.


printLarger (   sales1   ,   sales2   )  ;



 toThePowerOf is a method that accepts two  int arguments and returns the value of the first parameter raised to the power of the second. 

 An  int variable  cubeSide has already been declared and initialized. Another  int variable,  cubeVolume , has already been declared. 

 Write a statement that calls  toThePowerOf to compute the value of  cubeSide raised to the power of  3 and that stores this value in  cubeVolume . 

Assume that  toThePowerOf is defined in the same class that calls it.

cubeVolume  =  toThePowerOf (  cubeSide   , 3   )   ;



 max is a method that accepts two  int arguments and returns the value of the larger one. 

 Two  int variables,  population1 and  population2 , have already been declared and initialized. 

 Write an expression (not a statement!) whose value is the larger of  population1 and  population2 by calling  max . 

Assume that  max is defined in the same class that calls it.


max ( population1 , population2)



 Write the definition of a method  printDottedLine , which has no parameters and doesn't return anything. The method prints to standard output a single line (terminated by a newline) consisting of five periods. 


public static void printDottedLine ()
{
System.out.println(".....");
}



Write the definition of a method  printAttitude , which has an  int parameter and returns nothing. The method prints a message to standard output depending on the value of its parameter. 
If the parameter equals  1 , the method prints  disagree
If the parameter equals  2 , the method prints  no opinion
If the parameter equals  3 , the method prints  agree
In the case of other values, the method does nothing.

 Each message is printed on a line by itself. 


public          static       void        printAttitude      (    int      x    )

{

if          (           x       ==        1          )

{

System.out.println          (           "disagree"           )           ;

}

if            (         x         ==        2             )

{

System.out.println        (       "no opinion"           )         ;

}


if           (           x          ==         3         )

{

System.out.println            (           "agree"            )           ;

}


}



Write the definition of a method  printLarger , which has two  int parameters and returns nothing. The method prints the larger value of the two parameters to standard output on a single line by itself. 

public static void printLarger (int x,int y)
{
int z = Math.max(x,y);
System.out.println(z);
}


Declare and instantiate an array named  scores of twenty-five elements of type  int . 

int[] scores = new int[25];

Declare an array named  taxRates of   five  elements of type  double and initialize the elements (starting with the first) to the values  0.10 ,  0.15 ,  0.21 ,  0.28 ,  0.31 , respectively. 

double[] taxRates = { 0.10 , 0.15 , 0.21 , 0.28 , 0.31 } ;

Declare an array reference variable, week, and initialize it to an array containing the strings "mon", "tue", "wed", "thu", "fri", "sat", "sun" (in that order). 

String[ ] week = {"mon", "tue", "wed", "thu", "fri", "sat", "sun"};

Given that the array  monthSales of integers has already been declared and that its elements contain sales data for the 12 months of the year in order (i.e., January, February, etc.), write a statement that writes to standard output the element corresponding to October. 

 Do not write anything else out to standard output. 

System.out.println(monthSales[9]) ;


Given an array  temps of  double s, containing temperature data, compute the average temperature. Store the average in a variable called  avgTemp . Besides  temps and  avgTemp , you may use only two other variables -- an  int variable  k and a  double variable named  total , which have been declared. 

total = 0 ;
for( k = 0 ; k<temps.length ; k++ )
{
total = total + temps[k] ;
}
avgTemp = total/temps.length ;




Reversing the elements of an array involves swapping the corresponding elements of the array: the first with the last, the second with the next to the last, and so on, all the way to the middle of the array. 

 Given an array  a and two other  int variables,  k and  temp , write a loop that reverses the elements of the array. 


for( k=0 ; k<a.length/2 ; k++ )
{
temp = a[k] ;
a[k] = a[a.length - k - 1] ;
a[a.length - k - 1] = temp ;
}


printArray is a method that accepts one argument, an array of  int s. The method prints the contents of the array; it does not return a value. 

 inventory is an array of  int s that has been already declared and filled with values. 

 Write a statement that prints the contents of the array  inventory by calling the method  printArray . 


printArray( inventory ) ;




Write the definition of a method  printArray , which has one parameter, an array of  int s. The method does not return a value. The method prints out each element of the array, on a line by itself, in the order the elements appear in the array, and does not print anything else. 

public void printArray( int[] s )
{
for ( int i = 0 ; i < s.length ; i++ )
{
System.out.println(s[i]) ;
}
}




Given: 
 an  int variable  k , 
 an  int array  currentMembers that has been declared and initialized, 
 an  int variable  memberID that has been initialized, and 
 an  boolean variable  isAMember , 
 write code that assigns  true to  isAMember if the value of  memberID can be found in  currentMembers , and that assigns  false to  isAMember otherwise. Use only  k ,  currentMembers ,  memberID , and  isAMember . 

for ( k=0 ; k<currentMembers.length ; k++ )
{
if (memberID==currentMembers[k])
{
isAMember = true ;
break ;
}
else
{
isAMember = false ;
}
}