日期:2014-05-19  浏览次数:20747 次

很简单的问题:如何输入字母s以后,循环停止?
要求:这个循环要求输入最多100个数字。如果一直输入数字,一直循环。如果输入了特定字母s,这个循环停止。如果到了100次,也停止。如果输入的是非数字和非字母s,重新要求用户输入。

import java.io.*;

public class 123 {

  public static void main(String[] args) throws IOException {
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  int[] input = new int[100];
  for (int i = 0; i < 100; i++) {
  int num = 0;
  boolean stop = false;
  while (!stop) {
  try {
  System.out.print("Input: ");
  num = Integer.parseInt(in.readLine());
  stop = true;
  input[i] = num;
  } catch (NumberFormatException nfe) {
  System.out.println("Input is invalid.");
  }
  }
  }
}

这是我写的,但是不能在用户输入字母s的时候停止,请问怎么修改?

------解决方案--------------------
在你代码的基础上稍微改了一下。。。

Java code

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int[] input = new int[100];
        for (int i = 0; i < 100; i++) {
            int num = 0;
            boolean stop = false;
            while (!stop) {
                try {
                    System.out.print("Input: ");
                    String s = in.readLine();
                    if ("s".equals(s.toLowerCase())) {
                        return;
                    }
                    num = Integer.parseInt(s);
                    stop = true;
                    input[i] = num;
                } catch (NumberFormatException nfe) {
                    System.out.println("Input is invalid.Pls input again!");
                }
            }
        }
    }

------解决方案--------------------
while (!stop) {
try {
System.out.print("Input: ");
String str = in.readLine());
if ("s".equals(str.toLowerCase()) ){
break ;
}
num = Integer.parseInt(str);
input[i] = num;
} catch (NumberFormatException nfe) {
System.out.println("Input is invalid.");
}