Originally Posted by
Norm
The prompts the values of x and y must be done in the main method so that their values are changed there. Then those values should be passed to the multiplyInts method.
Yes! Finally my program works:
package randomExperiments;
import java.util.Scanner;
/*
Influenced from page 117 in textbook.
*/
public class StaticMethodExample {
private static Scanner sc = new Scanner(System.in);
public static String getString(String str) {
System.out.print("Enter a string for the str variable: ");
str = sc.nextLine();
return str;
}
//to call this method in another class: String myString = StaticMethodExample.getString(str);
public static void printMessage(){
System.out.println("Hello. I'm the static void method, printMessage().");
}
//to call this method in another class: StaticMethodExample.printMessage();
public static int multiplyInts(int x, int y){
int result = x * y;
return result;
}
//to call this method in another class: StaticMethodExample.multiplyInts(x, y);
}
package randomExperiments;
import java.util.Scanner;
import java.util.Random;
import static randomExperiments.StaticMethodExample.*;
public class RandomExperiments {
public static void main(String[] args){
int x = 0, y = 0, result = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter an int value for x: ");
x = input.nextInt();
System.out.println();
System.out.print("Enter an int value for y: ");
y = input.nextInt();
System.out.println();
String str = "";
String myString = StaticMethodExample.getString(str);
System.out.println("The string passed from the my string function is: " + myString);
StaticMethodExample.printMessage();
result = StaticMethodExample.multiplyInts(x, y);
System.out.println("You entered " + x + " for x, and " + y + " for y.\n");
System.out.println("x * y = " + result);
}
}
Output:
Enter an int value for x: 3
Enter an int value for y: 3
Enter a string for the str variable: dink
The string passed from the my string function is: dink
Hello. I'm the static void method, printMessage().
You entered 3 for x, and 3 for y.
x * y = 9
Originally Posted by
jim829
Ok, I get the impression that you don't fully understand what purpose a method serves.
The real stumbling block (for me) is managing scope, not understanding the idea of it. Before I declared x and y and initialized them to 0 in the main method, the dumb program wouldn't even let me pass the real x and y arguments to the function call. I guess I was expecting too much to happen in one method definition.
Thank you again, Jim and Norm.