打破 hasNext 循环
Break hasNext loop
我必须阅读一些 Int Vector。我把它放到ArrayList。
读取方法有自己的 class。
在主函数中,我创建了对象和启动方法 readMy,它将被放入值列表中,这些值在一行中输入,由 space 分隔。问题是循环次数结束后,没有完成。我怎样才能离开这个循环,除了 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());
}
}
}
我必须阅读一些 Int Vector。我把它放到ArrayList。 读取方法有自己的 class。 在主函数中,我创建了对象和启动方法 readMy,它将被放入值列表中,这些值在一行中输入,由 space 分隔。问题是循环次数结束后,没有完成。我怎样才能离开这个循环,除了 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());
}
}
}