java - 如何让java读取用户的文本字段并根据用户给出另一个变量?
问题描述
我有一个文本字段,用户只能在其中输入数字和一个标签,该标签根据在文本字段中输入的数字显示价格。
我需要 Java 能够读取输入到文本字段中的数字,并且在内部 java 将根据用户给出的输入提供另一个变量。
它就像一个范围刻度,它可以读取其中的值类型并根据范围自动给出分配的值。
String tourist = touristnumf.getText();
if(touristnumf.getText() > =10)
{
boolean tourbetweenonetoten = true;
}
解决方案
读取一个数字 ( userInput
) 并提供一个映射变量值:
import java.util.Map;
import java.util.HashMap;
public class StackOverflowTest {
public static void main(String args[]){
Map<Integer,Integer> translateMap = new HashMap<>();
translateMap.put(1,11);
translateMap.put(2,23);
translateMap.put(3,14);
Integer userInput = 2;
System.out.println("translated " + userInput
+ " into " + translateMap.get(userInput));
// prints:
// translated 2 into 23
}
}
或者对于范围:
public class StackOverflowTest {
public static void main(String args[]){
Integer userInput = 12;
Integer translated;
if (userInput > 20) {
translated = 100;
} else if (userInput > 10) {
translated = 50;
} else if (userInput > 0) {
translated = 250;
} else {
translated = 10000; // replace with exception handling
}
System.out.println("translated " + userInput
+ " into " + translated);
// prints:
// translated 12 into 50
}
}
两者结合的例子:
import java.util.Map;
import java.util.HashMap;
public class StackOverflowTest {
public static void main(String args[]){
Map<Integer,Integer> translateMap = new HashMap<>();
translateMap.put(0,250);
translateMap.put(1,50);
translateMap.put(2,100);
translateMap.put(3,5);
String userInput = "19";
// Converting a string into an Integer
Integer input = Integer.parseInt(userInput);
Integer translated;
// works to replace below if statement only
// because ranges happens to be devided into 10's
translated = translateMap.get(input/10); // automatic flooring of float to int.
/*
if (input > 20) {
translated = translateMap.get(2);
} else if (input > 10) {
translated = translateMap.get(1);
} else if (input > 0) {
translated = translateMap.get(0);
} else {
translated = 10000; // exception handling
}
*/
System.out.println("translated " + userInput
+ " into " + translated);
// prints:
// translated 19 into 50
}
}
推荐阅读
- oracle - oracle 表中的 CURRENT_TIMESTAMP
- c# - 以不同用户身份从备份恢复 SQL 数据库
- excel - 使用 VBA 将 ListColumn 从一个表复制到另一个表时没有错误也没有数据
- python - Pyinstaller - 错误消息:名称 Actor 未定义
- android - 如何在我的项目结构中设置位置?
- java - 如何在 mockito 中模拟地图?
- angular - 如果列表为空,如何禁用 mat-form-field 或 mat-autocomplete?
- python - 为什么这在 c++ 中不起作用但在 python 中起作用
- visual-studio - 在 CMake 中添加 gRPC::grpc++ 库依赖后,libprotocd.lib 的意外路径
- django - 将模型传递给模板时,类视图错误“未定义名称‘上下文’”