2008-09-22 45 views
5

我习惯于python,所以这对我有点困惑。我试图逐行接收输入,直到用户输入一定的数字。这些数字将被存储在一个数组中,以向它们应用一些统计数学。目前,我有一个主要课程,统计课程和一个“阅读”课程。Java中的ArrayList和输入

两个问题:

  1. 我似乎无法得到输入回路工作了,什么是这样做的最佳实践。

  2. 什么是读取方法的对象类型?一个double []或一个ArrayList?

    1. 如何声明方法类型是一个数组列表?

    2. 如何防止阵列中存储超过1000个值?

让我来展示一下我到目前为止有:

public static java.util.ArrayList readRange(double end_signal){ 
    //read in the range and stop at end_signal 

    ArrayList input = new ArrayList(); 
    Scanner kbd = new Scanner(System.in); 
    int count = 0; 
    do{ 
     input.add(kbd.nextDouble()); 
     System.out.println(input); //debugging 
     ++count; 
    } while(input(--count) != end_signal); 
    return input; 
} 

任何帮助,将不胜感激,原谅我... newbieness

回答

2

数目:

> 1。我似乎无法得到输入循环来解决问题,这样做的最佳做法是什么。

我宁愿有一个简单循环,而不是一个do {}而...和部位的条件的同时......在我的例子上面写着:

而读数不结束信号和计数低于限制:do。

> 2。阅读方法的目标类型是什么?一个double []或一个ArrayList?

然而,我强烈建议你使用List(java.util.List)接口来代替ArrayList。编程到接口而不是实现是一种很好的OO实践。

> 2.1如何声明方法类型为数组列表?

查看下面的代码。

> 2.2。如何防止数组中存储超过1000个值?

通过在while条件中添加此限制。

import java.util.Scanner; 
import java.util.List; 
import java.util.ArrayList; 

public class InputTest{ 

    private int INPUT_LIMIT = 10000; 

    public static void main(String [] args) { 
     InputTest test = new InputTest(); 
     System.out.println("Start typing numbers..."); 
     List list = test.readRange(2.0); 
     System.out.println("The input was " + list); 
    } 

    /** 
    * Read from the standar input until endSignal number is typed. 
    * Also limits the amount of entered numbers to 10000; 
    * @return a list with the numbers. 
    */ 
    public List readRange(double endSignal) { 
     List<Double> input = new ArrayList<Double>(); 
     Scanner kdb = new Scanner(System.in); 
     int count = 0; 
     double number = 0; 
     while((number = kdb.nextDouble()) != endSignal && count < INPUT_LIMIT){ 
      System.out.println(number); 
      input.add(number); 
     } 
     return input; 
    } 
} 

结束语:

最好是有 “实例方法” 比类方法。这样如果需要的话,可以通过子类来处理“readRange”而不必更改签名,因此在示例中,我已经删除了“static”关键字,创建了“InputTest”类的一个实例

在java代码风格的变量名应像在“endSignal”而不是“end_signal”一样在cammel情况下进行

5

你在你的循环需要什么条件:

while (input.get(input.size()-1) != end_signal); 

你正在做什么是德克莱姆引入计数器变量。你

也应申报ArrayList像这样:

ArrayList<Double> list = new ArrayList<Double>(); 

这使得列表类型特异性和允许的条件给出。否则有额外的铸造。

+0

您应该使用List接口而不是ArrayList。 列表 list = new ArrayList (); – Aaron 2008-09-22 20:00:15

0

**

public static java.util.ArrayList readRange(double end_signal) { 

    //read in the range and stop at end_signal 

    ArrayList input = new ArrayList(); 

    Scanner kbd = new Scanner(System. in); 
    int count = 0; 

    do { 
     input.add(Double.valueOf(kbd.next())); 
     System.out.println(input); //debugging 
     ++count; 
    } while (input(--count) != end_signal); 
    return input; 
} 

**

0

我认为你开始并不坏,但这里是我的建议。我将重点介绍代码下面的重要区别和要点:

包控制台;

import java.util。 ; import java.util.regex。;

公共类ArrayListInput {

public ArrayListInput() { 
    // as list 
    List<Double> readRange = readRange(1.5); 

    System.out.println(readRange); 
    // converted to an array 
    Double[] asArray = readRange.toArray(new Double[] {}); 
    System.out.println(Arrays.toString(asArray)); 
} 

public static List<Double> readRange(double endWith) { 
    String endSignal = String.valueOf(endWith); 
    List<Double> result = new ArrayList<Double>(); 
    Scanner input = new Scanner(System.in); 
    String next; 
    while (!(next = input.next().trim()).equals(endSignal)) { 
     if (isDouble(next)) { 
      Double doubleValue = Double.valueOf(next); 
      result.add(doubleValue); 
      System.out.println("> Input valid: " + doubleValue); 
     } else { 
      System.err.println("> Input invalid! Try again"); 
     } 
    } 
    // result.add(endWith); // uncomment, if last input should be in the result 
    return result; 
} 

public static boolean isDouble(String in) { 
    return Pattern.matches(fpRegex, in); 
} 

public static void main(String[] args) { 
    new ArrayListInput(); 
} 

private static final String Digits = "(\\p{Digit}+)"; 
private static final String HexDigits = "(\\p{XDigit}+)"; 
// an exponent is 'e' or 'E' followed by an optionally 
// signed decimal integer. 
private static final String Exp = "[eE][+-]?" + Digits; 
private static final String fpRegex = ("[\\x00-\\x20]*" + // Optional leading "whitespace" 
     "[+-]?(" + // Optional sign character 
     "NaN|" + // "NaN" string 
     "Infinity|" + // "Infinity" string 

     // A decimal floating-point string representing a finite positive 
     // number without a leading sign has at most five basic pieces: 
     // Digits . Digits ExponentPart FloatTypeSuffix 
     // 
     // Since this method allows integer-only strings as input 
     // in addition to strings of floating-point literals, the 
     // two sub-patterns below are simplifications of the grammar 
     // productions from the Java Language Specification, 2nd 
     // edition, section 3.10.2. 

     // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt 
     "(((" + Digits + "(\\.)?(" + Digits + "?)(" + Exp + ")?)|" + 

     // . Digits ExponentPart_opt FloatTypeSuffix_opt 
     "(\\.(" + Digits + ")(" + Exp + ")?)|" + 

     // Hexadecimal strings 
     "((" + 
     // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt 
     "(0[xX]" + HexDigits + "(\\.)?)|" + 

     // 0[xX] HexDigits_opt . HexDigits BinaryExponent 
     // FloatTypeSuffix_opt 
     "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + 

     ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*");// Optional 
                     // trailing 
                     // "whitespace" 

}

  1. 在Java中它的使用泛型一件好事。通过这种方式,您可以向编译器和虚拟机提供您即将使用的类型的提示。在这种情况下,它的双并宣布结果列表包含双重价值, 你能够使用的值没有铸造/类型转换:

    if (!readRange.isEmpty()) { 
        double last = readRange.get(readRange.size() - 1); 
    } 
    
  2. 与Java集合工作时,这是更好地回报接口,有许多特定列表的实现(LinkedList,SynchronizedLists,...)。因此,如果您稍后需要其他类型的List,则可以轻松更改方法内的具体实现,而无需更改任何其他代码。

  3. 您可能想知道为什么while控制语句有效,但正如您所看到的,next = input.next()。trim()。这样,变量赋值就在条件测试之前发生。此外微调需要FLASH播放器,以避免whitespacing问题

  4. 我不使用nextDouble()这里,因为每当用户将输入的东西是不是双,好了,你会得到一个异常。通过使用字符串,我可以解析用户给出的任何输入,但也可以根据结束信号进行测试。

  5. 可以肯定,一个用户真的输入了一个double,我使用了一个来自于Double.valueOf()方法的JavaDoc的正则表达式。如果此表达式匹配,则转换该值,否则将打印错误消息。

  6. 时使用的原因,我没有在你的代码中看到的计数器。如果您想知道成功输入了多少个值,请致电readRange.size()

  7. 如果你想用一个阵列上下工夫,在构造函数的第二部分展示了如何将它转换。

  8. 我希望你不是我糊涂了MIXIN双,双,但由于Java 1.5的特性自动装箱,这是没有问题的。而作为Scanner.next()不会返回NULL(据我所知),这should't是在所有问题。

  9. 如果你想限制数组的大小,使用

好吧,我希望你找到我的解决方案和解释有用的,使用result.size()作为指标和关键字打破离开while控制语句。

Greetz,GHad