Java 环路终止混淆
我有一段代码,可以在序列中输入一系列整数,但我想知道如何通过不输入任何值并按enter键来终止while循环。我知道如果x整数值为0,我可以设置一个条件,比如终止循环Java 环路终止混淆,java,loops,input,while-loop,Java,Loops,Input,While Loop,我有一段代码,可以在序列中输入一系列整数,但我想知道如何通过不输入任何值并按enter键来终止while循环。我知道如果x整数值为0,我可以设置一个条件,比如终止循环 public static void main(String[] args) { SimpleReader in = new SimpleReader1L(); SimpleWriter out = new SimpleWriter1L(); Sequence<Integer> s = new Sequ
public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
SimpleWriter out = new SimpleWriter1L();
Sequence<Integer> s = new Sequence1L<>();
Sequence<Integer> temp = s.newInstance();
System.out.println("Enter ");
int x = in.nextInteger();
int i = 0;
while (in.nextLine()) {
s.add(i, x);
x = in.nextInteger();
i++;
}
System.out.println(s);
}
publicstaticvoidmain(字符串[]args){
SimpleReader in=新SimpleReader1L();
SimpleWriter out=新的SimpleWriter1L();
序列s=新序列1L();
序列temp=s.newInstance();
系统输出打印项次(“输入”);
int x=in.nextInteger();
int i=0;
while(在.nextLine()中){
s、 加(i,x);
x=in.nextingeter();
i++;
}
系统输出打印项次;
}
break
可用于退出循环。所以你可以这样说:
如果(x==0)中断代码>就在语句i++之前代码>使用do while循环,如下所示:
do {
input = int.nextInteger();
s.add(i, x);
i++;
} while (input != 0);
或者在您的案例中使用while循环
while (in.nextLine()) {//assuming it checks if user has input
s.add(i, x);
x = in.nextInteger();//assuming this api gives integer value back if user indeed entered one
if (x == 0)
break;
i++;
}
如果你想达到你所描述的目的,你需要改变你阅读输入的方式——什么也不输入
首先使用while(in.nextLine())
会从输入中多消耗一行。因此,一半的输入行丢失了
我建议读一行,比如stringline=in.nextLine()
。然后是:
if (line.equals("")) break;
int x = Integer.parseInt(line);
抱歉,最近没有使用java来提供整个循环。但我认为你应该明白这一点。按enter键,不输入任何值
while (in.nextLine().length() > 0) {
s.add(i, x);
x = in.nextInteger();
i++;
}
循环终止。由于=
操作返回的值与它设置的值相同,因此您也可以稍微修改它:
SimpleReader in = new SimpleReader1L();
Sequence<Integer> s = new Sequence1L<>();
System.out.println("Enter ");
int i = 0;
String line = "";
while (!(line = ir.readLine()).trim().isEmpty()) {
x = Integer.parseInt(line);
s.add(i, x);
i++;
}
System.out.println(s);
SimpleReader in=new SimpleReader1L();
序列s=新序列1L();
系统输出打印项次(“输入”);
int i=0;
字符串行=”;
而(!(line=ir.readLine()).trim().isEmpty()){
x=整数.parseInt(行);
s、 加(i,x);
i++;
}
系统输出打印项次;
外加一个@Lemons12345;(这个问题提得很详细)但下次你问的时候,别忘了给语言加上标签。如果我把这个条件设为(x!=0)也是一样吗?@Bathsheba,很好,在这个社区里有像你这样的帅哥。