如何从数组JOptionPane中获取内容并将其用于计算

时间:2014-11-04 00:27:39

标签: java arrays

我在一个循环中有一个数组和两个jOPtionPanes。我想知道,如何在循环之外使用输入的值进行计算?

这是示例代码..

   String[] test = new String[2];
   int[] test = new int[2];

   for(int i = 1; i<2; i++)
   {
    String t1 = JOptionPane.showInputDialog(null,"enter any string value");
    int t2 = JOptionPane.showInputDialog(null,"enter integer value");

    test1[i] = t1;
    test2[i] = t2;

   }

现在类似于值= t2 +(10 * 3),但显然这不起作用。

我该怎么办?

this is my full code

2 个答案:

答案 0 :(得分:0)

实际上你不需要在循环之外声明a和b,因为你没有在循环之外访问它们。当你计算平均值时,你需要计算所有年龄,所以把变量放在一边并添加年龄到了。并且没有必要在String .use int数组中存储年龄..

double agecount = 0;

并在java int/int ==int中。如果你将一个int除以int,你得到一个int值,但对于平均int不好,你可以使用double。因为这样做了一个变量double agecount。你必须将一个int强制转换为double

double avarageAge = agecount /  names.length; 

并且不要忘记java数组索引是基于零的。你要将第一个元素留空[默认值]。

for (int i =1; i < names.length; i++)

更改为

for (int i = 0; i < names.length; i++)

示例代码

public static void users() {

        String[] names = new String[5];
        int[] ages = new int[5];


        for (int i = 0; i < names.length; i++) {

            String a = JOptionPane.showInputDialog(null, "What's your name, user " + (i+1) + "?");
            int b = Integer.parseInt(JOptionPane.showInputDialog(null, "What is your age, " + a + "?"));

            names[i] = a;
            ages[i] = b;

        }

        double agecount = 0;

        for (int i = 0; i < names.length; i++) {
            agecount += ages[i];
            System.out.println("User " + (i+1) + ":  " + names[i] + " " + ages[i] + " years old");
        }
        double avarageAge = agecount /names.length;

        System.out.println("The avarage age for this quiz is " + avarageAge);

    }

样本输入的输出&gt;&gt;

User 1:  u1 22 years old
User 2:  u2 10 years old
User 3:  u3 15 years old
User 4:  u4 54 years old
User 5:  u5 12 years old
The avarage age for this quiz is 22.6

答案 1 :(得分:-2)

我发现了这个here

我会查看链接以获得解释

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class Test {
    public static void main(String[] args) throws Exception{
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String foo = "40+2";
    System.out.println(engine.eval(foo));
    } 
}
希望这有帮助!