#java #methods
#java #методы
Вопрос:
Кто-нибудь может помочь решить эту проблему? Я создаю Java-программу, которая покажет набор вариантов, которые будут запускать выбранную программу пользователем с использованием методов java. Как я могу инициализировать переменную? Я поместил комментарий, где ошибка. Вот программа.
public static void main(String[] args) {
performProgram();
chooseNumber();
}
public static void performProgram(){
int number;
Scanner pj= new Scanner(System.in);
System.out.println("Please select a number that indicates what the program will perform");
chooseOption();
System.out.print("Enter the number of your choice: ");
number=pj.nextInt();
}
public static void chooseOption(){
System.out.println("1. Display the factors of a number");
System.out.println("2. Display whether a number is odd or even");
System.out.println("3. Display whether a number is a perfect number or not");
System.out.println("4. Display the elements of an array in ascending order");
System.out.println("5. Display the sum of odd elements in the array");
}
public static void chooseNumber(){
int number;
//Error: variable might have not been initialized
if(number == 1)
getFactors();
if(number == 2)
displayOddEven();
}
public static void getFactors(){
Scanner rz= new Scanner(System.in);
System.out.print("Enter a number: ");
int number=rz.nextInt();
System.out.print("The factors of" number " are: ");
for(int i=1; i<=number; i ){
if (number % i == 0){
System.out.print(i " ");
}
}
}
public static void displayOddEven(){
Scanner gd= new Scanner (System.in);
System.out.print("Enter a number: ");
int number=gd.nextInt();
if(number % 2 == 0)
System.out.print(number "is an even number.");
else
System.out.print(number "is an odd number.");
}
}
Комментарии:
1. Пожалуйста, обратите внимание, что Java не является JavaScript.
2. Верните число из
performProgram()
и передайте егоchooseNumber()
в.3. Если я изменю его на 0, он не перейдет к следующей программе.
4. Мой плохой. спасибо за исправление.
5. Как бы я это написал?
Ответ №1:
Из первого метода вы получаете числовое значение, возвращаете это значение и передаете его в качестве параметра второму методу. В вашей реализации сейчас второй метод не знает, какое значение ввел пользователь.
Комментарии:
1. Большое вам спасибо за ваш ответ!
Ответ №2:
В Java, когда вы создаете локальную переменную, вы должны их инициализировать, то есть присвоить им значение. Локальные переменные не имеют значения по умолчанию. Вот почему вы видите эту ошибку в методе chooseNumber.
Чтобы заставить ваш код работать, это один из способов, которым вы можете написать свою программу:
public static void main(String[] args) {
int number = performProgram();
chooseNumber(number);
}
public static int performProgram(){
int number;
Scanner pj= new Scanner(System.in);
System.out.println("Please select a number that indicates what the program will perform");
chooseOption();
System.out.print("Enter the number of your choice: ");
number=pj.nextInt();
return number
}
public static void chooseOption(){
System.out.println("1. Display the factors of a number");
System.out.println("2. Display whether a number is odd or even");
System.out.println("3. Display whether a number is a perfect number or not");
System.out.println("4. Display the elements of an array in ascending order");
System.out.println("5. Display the sum of odd elements in the array");
}
public static void chooseNumber(int number){
//Error: variable might have not been initialized
if(number == 1)
getFactors();
if(number == 2)
displayOddEven();
}
public static void getFactors(){
Scanner rz= new Scanner(System.in);
System.out.print("Enter a number: ");
int number=rz.nextInt();
System.out.print("The factors of" number " are: ");
for(int i=1; i<=number; i ){
if (number % i == 0){
System.out.print(i " ");
}
}
}
public static void displayOddEven(){
Scanner gd= new Scanner (System.in);
System.out.print("Enter a number: ");
int number=gd.nextInt();
if(number % 2 == 0)
System.out.print(number "is an even number.");
else
System.out.print(number "is an odd number.");
}
Комментарии:
1. Большое вам спасибо за вашу помощь!