【发布时间】:2014-02-25 04:30:57
【问题描述】:
我做了一些研究,但一无所获,所以我需要帮助从用户输入中读取泛型类型。假设我想输入一个整数,然后当我再次运行程序时,我想输入一个字符串。我将如何使用扫描仪或其他输入阅读器来做到这一点?这是我的代码
public class array <T,E> {
private T [] a;
private int size;
private int location;
private E add;
private E delete;
private E find;
public array(){
}
public array(int size){
this.size = size;
this.location = 0;
this.a = (T[])(new Object[size]);
}
public boolean add(T element){
if(location == size){
return false;
}else{
this.a[location++] = element;
System.out.println("Element added at location " + location);
return true;
}
}
public int find(T element){
for(int i = 0 ; i < location; i ++){
if(a[i] == element){
System.out.println("Element found at location " + i);
return i;
}
}
System.out.println("Couldn't find element");
return -1;
}
public boolean delete(T element){
int loc = find(element);
if(loc == -1){
System.out.println("Couldn't find element");
return false;
}else{
for(int x = loc; x < location - 1; x++){
a[x] = a[x+1];
}
System.out.println("Element deleted");
location -= 1;
return true;
}
}
public void go(){
DataInputStream in = new DataInputStream(System.in);
Scanner scanner = new Scanner(System.in);
array a = null;
int choice = 0;
System.out.println("Chose what you want to do");
System.out.println("1: Add a value");
System.out.println("2: Delete a value");
System.out.println("3: Find a value and return the index");
System.out.println("4: Display all elements in array");
System.out.println("5: Exit");
System.out.println();
try{
choice = scanner.nextInt();
}catch(Exception e){
System.out.println("Incorrect input");
go();
}
switch(choice){
case 1:
System.out.println("Enter the element you want to add");
add = in.read();
a.add(add);
break;
case 2:
System.out.println("Enter the element you want to delete");
delete = in.nextInt();
a.delete(delete);
break;
case 3:
System.out.println("Enter the element you want to find");
find = in.nextInt();
a.find(find);
break;
case 4:
System.out.println(a.toString());
break;
case 5:
System.exit(0);
break;
}
System.out.println("Continue? 1-Yes, 2-No");
int yn = in.nextInt();
if(yn == 1){
go();
}else{
System.exit(0);
}
}
@Override
public String toString(){
String string = "";
for(int i = 0; i < location; i++){
string = string + " " + a[i];
}
return "Numbers " + string;
}
}
这是我的主要课程(司机)
public class ArrayManipulator<T> {
private static int size;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
array a = new array();
System.out.println("Enter the size of the array");
size = in.nextInt();
System.out.println("---------------------------");
a = new array(size);
a.go();
}
}
所以,我的问题是要求用户在 go() 方法中为数组中的元素输入值。我不知道使用哪个输入阅读器来阅读泛型类型,或者是否可能。谢谢
【问题讨论】: