Write a program that will call another method, max, to determine the maximum of two…
- User
Write a program that will call another method, max, to determine the maximum of two numbers. Method max should return the maximum value. For example, if the user entered two numbers 2, and 5 from main method and called max method the max method should return 5 to the main method.
- Assistant
Here's a code example in Java:
codepublic class MaxFinder { public static void main(String[] args) { int a = 2; int b = 5; int max = max(a, b); System.out.println("The maximum of " + a + " and " + b + " is: " + max); } public static int max(int num1, int num2) { if (num1 > num2) { return num1; } else { return num2; } } }Output:
codeThe maximum of 2 and 5 is: 5 - User
i want the user to input the numbers
- Assistant
In that case, you can modify the code to take input from the user instead of using hardcoded values. Here's an updated example:
codeimport java.util.Scanner; public class MaxFinder { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); int a = scanner.nextInt(); System.out.print("Enter the second number: "); int b = scanner.nextInt(); int max = max(a, b); System.out.println("The maximum of " + a + " and " + b + " is: " + max); scanner.close(); } public static int max(int num1, int num2) { if (num1 > num2) { return num1; } else { return num2; } } }Output:
codeEnter the first number: 2 Enter the second number: 5 The maximum of 2 and 5 is: 5 - User
Define a method named printGrade and calls it from main method to print the grade based on a given score. For example, if the user entered a score 80 from main method, then called printGrade method it will print “B” grade from inside its body.
- Assistant
Here's a Java code example that defines a method named
printGradeand calls it from themainmethod:codeimport java.util.Scanner; public class GradeCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the score: "); int score = scanner.nextInt(); printGrade(score); scanner.close(); } public static void printGrade(int score) { if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else if (score >= 70) { System.out.println("C"); } else if (score >= 60) { System.out.println("D"); } else { System.out.println("F"); } } }In this example, the
mainmethod takes input from the user for the score and passes it to the method. The method checks the score and prints the corresponding grade.