C while循环额外迭代

时间:2015-07-31 06:52:13

标签: c while-loop iteration

我尝试输入验证scanf功能。我已修复输入以忽略空格("%c ....")。

任何人都可以看到我做错了吗?

public class Client extends Activity {

private Socket socket;

private static final int SERVERPORT = 8099;
private static final String SERVER_IP = "10.0.0.3";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);      

    new Thread(new ClientThread()).start();
}

public void onClick(View view) {
    try {
        EditText et = (EditText) findViewById(R.id.EditText01);
        String str = et.getText().toString();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())),
                true);
        out.println(str);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

class ClientThread implements Runnable {

    @Override
    public void run() {

        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

            socket = new Socket(serverAddr, SERVERPORT);

        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

}

3 个答案:

答案 0 :(得分:1)

首先,变量done未初始化且具有不确定值

int k, done;
//...
while(done != 1){

您必须初始化它,例如

int k, done = 0;

但是写一个更合适的循环会更好。这不是while循环,而是使用do-while循环更好。例如

int done = 0;
//...

do
{
    printf("\n%s\n%s\n%s\n%s", "Input the following: three characters,", " an int,", " a float,", " and a double: \n");
    if(scanf(" %c%c%c%d%f%lf", &c1, &c2, &c3, &k, &x, &y) == 6){
      printf("\nHere is the data that you typed in: \n");
      printf("%3c%3c%3c%5d%17e%17e\n\n", c1, c2, c3, k, x, y);
      done = 1;
    } else {
      printf("Invalid input!");
    }
} while ( done != 1 );

其次在scanf调用中,您应该为格式说明符%c

指定balnks

例如

    if(scanf(" %c %c %c%d%f%lf", &c1, &c2, &c3, &k, &x, &y) == 6){

答案 1 :(得分:0)

您忘了初始化变量。至少应将done初始化为不是1的内容。

答案 2 :(得分:0)

您忘记阅读并丢弃无效输入行的其余部分。添加e。克。

        scanf("%*[^\n]%*c");

else区块中。