首页 > 解决方案 > 如何让java读取用户的文本字段并根据用户给出另一个变量?

问题描述

我有一个文本字段,用户只能在其中输入数字和一个标签,该标签根据在文本字段中输入的数字显示价格。

我需要 Java 能够读取输入到文本字段中的数字,并且在内部 java 将根据用户给出的输入提供另一个变量。

它就像一个范围刻度,它可以读取其中的值类型并根据范围自动给出分配的值。

 String tourist = touristnumf.getText();
 if(touristnumf.getText() > =10)
        {
           boolean tourbetweenonetoten = true;
        }

标签: java

解决方案


读取一个数字 ( 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
  }
}

推荐阅读