3 回答

TA貢獻1835條經驗 獲得超7個贊
請查看此內容,您正在string與進行比較integer,
if (user_answer.equals(correct_answer))
這可能會幫助您:
import java.util.Scanner;
class Main {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generateRandom(max_value, min_value);
double x_value = generateRandom(max_value, min_value);
double b_value = generateRandom(max_value, min_value);
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
checkAnswer(m_value, x_value, b_value);
}
private static void checkAnswer(double m_value, double x_value, double b_value) {
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int) m_value * (int) x_value + (int) b_value;
if (user_answer.equals(String.valueOf(correct_answer))) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
user_input.close();
}
}
static int generateRandom(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)
+ 1)) + min_value);
}
}

TA貢獻1890條經驗 獲得超9個贊
從技術上講,您已經正確解決了問題,您正在使用一種或多種方法,但也許您嘗試做的是一種稱為提取方法/提取函數重構的常見代碼重構,執行這種類型的重構會產生更具可讀性和可維護性的代碼,并且很容易做到。
作為初學者,請識別重復或看起來相似的代碼,在您的情況下,以下幾行看起來適合 extract 方法:
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
請注意,每行的 RHS 是相同的,因此我們可以用如下方法調用替換顯式代碼:
double m_value = getRandomDoubleBetween(max_value, min_value);
double x_value = getRandomDoubleBetween(max_value, min_value);
double b_value = getRandomDoubleBetween(max_value, min_value);
private double getRandomDoubleBetween(double max_value, double min_value) {
return (int)(Math.random()*((max_value-min_value)+1))+min_value;
}
您可以識別代碼的其他區域,這些區域要么包含重復,要么可能包含一些難以理解的代碼,如果將其提取到一個具有揭示代碼正在做什么的名稱的方法中,這些代碼會更容易理解。

TA貢獻1811條經驗 獲得超5個贊
這是方法的快速概述,因此尚未完全完成。如果您需要更多幫助,請詢問!祝你作業順利,成為野獸開發者之一!
public class Main {
public static void main(String[] args) {
int a = 1; // give a value of 1
methodTwo(a); // sending the int a into another method
}
// Here's method number two
static void methodTwo (int a) { // it gives a's type and value
System.out.println(a); //Gives out a's value, which is 1
}
}
添加回答
舉報