【问题标题】:Android Studio Java - First array to display index values from second arrayAndroid Studio Java - 第一个数组显示第二个数组的索引值
【发布时间】:2018-12-03 02:11:53
【问题描述】:

我有一个名为 Inputs1 的“EditText”,用于输入值以使用“If”语句与数组 example1 进行比较。

名为 example1 的数组具有以下值:5、10、15、20、25、30

Outputs1 用于显示来自数组example1的值

此外,名为 example2 的数组具有以下值:105、110、115、120、125、130

Outputs2 用于使用数组example1 中的索引值显示数组example2 中的值

例子:

Inputs1 的值为:20

Outputs1 显示值:20

Outputs2 应该显示值:120

我什至让Outputs1 显示值:20,但我无法获得Outputs2 的代码来显示值:120。

请有上述经验或知识的人帮助我?

谢谢。

代码:

    public class exampleOutput extends AppCompatActivity {

    Editable text;
    EditText Inputs1;
    TextView Outputs1;
    TextView Outputs2;
    Integer arrayIndex;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example_output);

        Outputs1 = (TextView) findViewById(R.id.Outputs1);
        Inputs1 = (EditText) findViewById(R.id.Inputs1);
        text = Inputs1.getText();
        Outputs2 = (TextView) findViewById(R.id.Outputs2);



    }

    final String[] example1 = {("5"), ("10"), ("15"), ("20"), ("25"), ("30")};
    final String[] example2 = {("105"), ("110"), ("115"), ("120"), ("125"), ("130")};


    public void displayExample(View v) {

        if (Arrays.asList(example1).contains(Inputs1.getText().toString())) {

            Outputs1.setText("You typed in: " + text + ", which is correct!");
            arrayIndex = (Arrays.asList(example1).indexOf(Inputs1.getText().toString()));
            Outputs2.setText("Your second number is: [The value from the second array] " +  ", the index is: " + arrayIndex + "!");

            } else {

            Outputs1.setText("Please type in a number 1-5.");
            Outputs2.setText("");

      }

   }

}

【问题讨论】:

  • 请发布您的代码,了解如何获得 Label1 的价值
  • 你当前的密码是多少?

标签: java android arrays if-statement indexing


【解决方案1】:

你可以使用

int indexFromLabel1 = array1.indexOf(valueWhoseIndexYouNeed);

然后,如果我理解正确,您想在 Array2 中显示此索引处的值。 这个你一定已经想通了

int valueFromArray2 = array2[indexFromLabel1 ];

这是假设我正确理解了场景。

更好的是,您应该检查 Array2 中是否存在所需的索引,像这样

if( indexFromLabel1 < array2.length() ){
    int valueFromArray2 = array2[indexFromLabel1 ];
}else {
    //Do your logic

}

【讨论】:

  • 由于array2[indexFromLabel1 ],这有效,感谢您帮助我,我试图弄清楚如何打印该值。
  • 很高兴听到这个消息。
【解决方案2】:

看起来你从不打印 example2 数组中的值

尝试更改此行:

Outputs2.setText("Your second number is: [The value from the second array] " +  ", the index is: " + arrayIndex + "!");

到这里:

Outputs2.setText("Your second number is: [The value from the second array] " + example2[arrayIndex] + ", the index is: " + arrayIndex + "!");

【讨论】:

  • 我尝试打印该值,但我不知道如何打印,现在由于+ example2[arrayIndex],它可以工作,感谢您帮助我。可悲的是,对方先回复了,所以我不能把它作为正确的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
相关资源
最近更新 更多