Scanner in=new Scanner(System.in);
String[] input = new String[26];
for(int i = 0; input[i] != "end"; i++){
input[i] = in.next();
}
in.close();
想要达到的效果:执行程序后由键盘输入:
thisisthefistline
thisisthesecondline
end
结束输入,进入下一行程序。
但是事实上,即使输入了end,按下回车后,依然可以继续输入字符串和回车。
想要知道,如果我需要使这个代码停下来执行下一段代码,在for中应该用什么替换“input[i] != "end"”,以及相应的是如何停止键盘录入的?
字符串不能用“=”、“!=”之类的比较。还有用for语句他是先判断后执行语句。下面代码可以实现:enter code here
Scanner in = new Scanner(System.in);
String[] input = new String[26];
int i = 0;
do {
input[i] = in.next();
i++;
} while (!input[i - 1] .equals("end") );
in.close();
String 数组长度已经定了,暂停有错误,考虑用StringBuffier或者StringBudder
String[] strs = new String[26];
Scanner sc = new Scanner(System.in);
String s;
int i = 0;
//字符串用equals比较,equals前面能用固定串的用固定串,因为equals前用null会出空指针
while (!"end".equals(s=sc.nextLine())){
//不够位置放,长度扩展为原来的2倍,就可以无限输入了
if(i==strs.length){
String[] copy = new String[strs.length<<1];
System.arraycopy(strs,0,copy,0,strs.length);
strs = copy;
}
strs[i++] = s;
}
sc.close();
System.out.println(Arrays.toString(strs));//Arrays.toString()和Arrays.deepToString()超好用,强烈推荐