Chapter 5 My Programming Lab
The Math class provides a static method, max, 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.
Math.max(population1,population2)
1. A showChar Method Write a method named showChar. The method should accept two arguments: a reference to a String object and an integer. The integer argument is a character position within the String, with the first character being at position 0. When the method executes, it should display the character at that character position. The method does not return anything. Here is an example of a call to the method: showChar("New York", 2); In this call, the method will display the character w because it is in position 2. Demonstrate the method in a complete program.
import java.util.Scanner; public class Method_showChar { public static void main(String[] args) { String lineOfText; int index; Scanner stdin = new Scanner(System.in); System.out.print("Enter a line of text:"); lineOfText = stdin.nextLine(); System.out.print(" Enter your index: "); index = stdin.nextInt(); showChar(lineOfText,index); } public static void showChar(String str, int index) { System.out.print(str.charAt(index)); } }
Write a method max that has two string parameters and returns the larger of the two.
public String max(String a, String b) { return a.compareTo(b) > 0 ? a : b; }
Write the definition of a method max that has three int parameters and returns the largest.
public static int max(int a, int b, int c) { return Math.max(Math.max(a,b),c); }
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 static int twice(int num) { int twiceNum = 2 * num; return twiceNum; }
Write the definition of a method dashedLine, with one parameter, an int. If the parameter is negative or zero, the method does nothing. Otherwise it prints a complete line terminated by a newline to standard output consisting of dashes (hyphens) with the parameter's value determining the number of dashes. The method returns nothing.
public static void dashedLine(int numDashes) { for (int i = 0; i < numDashes; i++) { System.out.print("-"); } System.out.println(); }
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 num1, int num2) { System.out.println((num1 > num2 ? num1: num2)); }