logic java_Logic Error in Java For-loop

可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:

问题:

I am trying to make the loop continue to execute here until the user types the letter S at the keyboard. It seems to be giving three outputs instead of one for each iteration. What am I doing wrong here;

// Loop until an S is typed

public class ForTest {

public static void main(String[] args)

throws java.io.IOException {

int i;

System.out.println("Type S to stop.");

for(i = 0; (char) System.in.read() != 'S'; i++)

// System.out.println("print");

System.out.println("Pass # " + i);

// System.out.println("print");

}

}

Output coming up is if I press 'a':

Type S to stop.

a

Pass # 0

Pass # 1

Pass # 2

回答1:

The InputStream.read method block until the end of input which is on a Windows OS the control characters CR LF (rn).

This explains why you get 3 characters as a result.

See for yourself :

public static void main(String[] args) throws java.io.IOException {

int i;

System.out.println("Type S to stop.");

char c = (char) 0;

for (i = 0; c != 'S'; i++) {

c = (char) System.in.read();

System.out.println("Pass # " + i);

System.out.println("char intValue : " + (int) c);

}

}

回答2:

System.in will use BufferedInputSteam to read the input from console bit by bit (including the line break, etc). In Mac system, I get 2 bits whenever i gave a single digit input.

Use Scanner and read all the bytes and convert as String.

回答3:

I suggest you to avoid reading input in that way, use Scanner instead. You can reach your goal with this code:

int i = 0;

Scanner scan = new Scanner(System.in);

System.out.println("Type S to stop.");

while( !scan.next().equals("S")) {

i++;

System.out.println("Pass # "+i);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值