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
}
}
添加回答
举报