Eine Klasse für Sammler
import java.util.*;
public class Lister {
public List<String> fillList() {
java.util.Scanner userInput = new java.util.Scanner(System.in);
List<String> collected = new LinkedList<String>();
String next = "na";
while (userInput.hasNext()) {
next = userInput.next();
collected.add(next);
if (next.contentEquals("ende")) {
break;
}
}
System.out.println(collected);
System.out.println(collected.size());
userInput.close();
return collected;
}
public int countListItems(List<String> list) {
int i =0;
i=list.size();
return i;
}
public int countListItems(List<String> list, String type) {
int i =0;
i=list.size();
if (type.contentEquals("num")) {
i=i - countListStrings(list);
}
if (type.contentEquals("str")) {
i=countListStrings(list);
}
return i;
}
public int countListStrings(List<String> list) {
int i =0;
int is =0;
while (i < list.size()) {
String next=list.get(i);
if (!next.matches("\\d+(\\.\\d+)?")) {
is++;
}
i++;
}
return is;
}
public Double[] getNumberArray(List<String> list) {
int size=countListItems(list,"num");
Double[] NumberArray = new Double[size];
int i=0;
while (i < size) {
String next=list.get(i);
if (next.matches("\\d+(\\.\\d+)?")) {
NumberArray[i]=Double.parseDouble(next);
}
i++;
}
System.out.println(NumberArray.length);
return NumberArray;
}
}
Anwendung:
public static void main(String[] args) {
System.out.println("Hallo Leute");
Lister list=new Lister();
List<String> flist=list.fillList();
System.out.println("Total Items: "+list.countListItems(flist));
System.out.println("Strings: "+list.countListStrings(flist));
System.out.println("Numbers: "+list.countListItems(flist,"num"));
System.out.println("Array: "+list.getNumberArray(flist).length);
}