我必须读取一些Int Vector.我把它放到ArrayList.Methods来读取有自己的类。我把它放到ArrayList.Methods to read have own class.In main function I create object and start method readMy which is to be put in the list of values which are entered on one line separated by a space.在主函数中,我创建了一个对象,并启动了方法readMy,它将被放在用空格隔开的值列表中,问题是在循环次数结束后,我如何才能离开这个循环,除了ctrl + d。问题是在循环次数结束后,没有完成。
public class Wektory
{
List<Integer> wektor = new ArrayList<Integer>();
public Wektory(){}
public void readMy()
{
Scanner C=new Scanner(System.in);
while(C.hasNextInt())
wektor.add(C.nextInt());
}
}
我检查了列表的内容,是正确的。
我不知道我是否理解你的观点,但你可以做这样的事情。
Scanner C=new Scanner(System.in);
boolean quit = false;
while (!quit){
System.out.println("please enter the values : \r");
if(C.hasNextInt()){
int value = C.nextInt();
C.nextLine();
wektor.add(value);
}
// to end you can do this or you can break directly :
if(wektor.size() >= 10){
System.out.println("the loop has been ended");
quit =true;
}
}
你可以用一个唯一的int值来退出扫描器,例如: -1。
public class Wektory
{
List<Integer> wektor = new ArrayList<Integer>();
public Wektory(){}
public void readMy()
{
Scanner C=new Scanner(System.in);
while(C.hasNextInt()){
int val = C.nextInt();
if(val==-1){
break;
}
wektor.add(C.nextInt());
}
}
}