我们如何在 Android java 中从两个值中获取一个值?

How can we get one value back of two values in Android java?

提问人:Best Thinking 提问时间:3/25/2023 更新时间:3/25/2023 访问量:34

问:

我们怎样才能从两个值中取回一个值?例如,如果用户写 100,我们如何在文本框中将 100 替换为 50+50?也就是说,假设用户键入 100 并在按下按钮时,文本框应显示 50+50 或 75+25 等,而不是 100,依此类推,等于 100。一个朋友推荐我,但我想为用户提供低和高的价值。也就是说,如果用户写 100,它应该显示为 75+25 或 80+20 等。谢谢

    int customerInput = 100; //getvalue from user
        int splitValue = customerInput/2;
       saif.setText(splitValue+"+"+splitValue);
java android 数学

评论


答:

0赞 galalem 3/25/2023 #1

您仍然可以使用您的代码,但稍作改动

int customerInput = 100; //getvalue from user
int half = customerInput/2;
int splitValue = new Random().nextInt(1, half+1);
saif.setText((customerInput - splitValue) + " + " + splitValue);

请注意,这不适用于低于 1 的数字。如果您确实需要它们,请对 1 和 0 使用条件,对负数使用简单的 abs

另一种方法是使用 sqrt

int customerInput = 100; //getvalue from user
int splitValue = (int) Math.floor(Math.sqrt(customerInput));
saif.setText((customerInput - splitValue) + " + " + splitValue);

评论

0赞 Best Thinking 3/25/2023
对不起,出现此错误。方法 Random.nextInt() 不适用
0赞 galalem 3/25/2023
@BestThinking 根据您的 Java 版本,它是 ,如果它只接受一个参数,则使用 如果 Random 它根本不存在,您仍然可以使用java.util.Randomnew Random().nextInt(half) + 1(int) ((Math.random() * half) + 1)
0赞 TheGix 3/25/2023 #2

您需要的低点和高点是什么?

在您的示例中,它是 1/4 和 3/4,因此这将为您提供:

  int customerInput = 100; //getvalue from user
  int splitValue1 = customerInput/4;
  int splitValue2 = (customerInput/4)*3;
  saif.setText(splitValue+"+"+splitValue);

如果你需要它是随机的,你可以使用 Java 函数

int 随机 = Random.nextInt(n)

这将返回一个范围为 [0, n-1] 的随机 int。 因此,在您的情况下,您需要一个介于 0 和 100 之间的随机数

int customerInput = 100; //getvalue from user 
int random = new Random().nextInt(100); // [0, 100]
int random2 = 100 - random; // the other percent of your number
saif.setText(random+"+"+random2);

评论

0赞 Best Thinking 3/25/2023
谢谢,根据我的阶段改变后工作完美。
0赞 Emmanuel 3/25/2023
如果输入值不是 4 的倍数,则第一种方法中断!、 和 的输入都给你 和 。1001011021032575
0赞 Emmanuel 3/25/2023 #3

您要实现的是将一个值拆分为两个:较小的数字和较大的数字。

您需要确定获取其中一个数字的策略,例如,分数(可以是固定的或随机的)。此后,您通过减法计算另一个数字。 您可以使用固定分数(十进制)。

int number = getUserInput();
double fraction = getFraction();
int numA = (int)(fraction * number);
int numB = number - numA;

您的方法可以返回固定分数或随机分数(如果需要随机性)。getFraction

这可能是:

double getFraction(){
   return 0.25; //This should be a public static final field in your class
}

或类似的东西:

double getRandomFraction(){
   Random random = new Random(); //This could be a variable in the class
   int nominator = 1 + random.nextInt(9); //Gives you a random int between 1 and 9
   int denominator = 10;
   return (double)nominator / denominator;
}