如何解决如何做第二个柜台
我正在尝试使用do-while循环创建第二个计数器,该循环在用户输入等于q时停止。但是我不知道如何使计数器计数秒,这是我的代码:
city - [city01,city04,city01002]
state- [state02,state03,statebg]
country - [countrywq,countrypo]
输出是这个:
public class Search {
static public void main(String args[]) throws IOException {
int seconds = 0;
System.out.println("Insert q to stop:");
char i;
i = (char) System.in.read();
do {
seconds++;
} while(i != 'q');
}
}
解决方法
以下一行应在循环之内。
i = (char) System.in.read();
,
如果您打算以秒为单位输入输入q的时间,那么下面的代码将做到这一点
public class Search {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
Scanner sc = new Scanner(System.in);
char i;
do {
System.out.print("Insert q to stop:");
String str = sc.next();
i = str.charAt(0);
} while (i != 'q');
long endTime = System.currentTimeMillis();
double executionTime = (endTime - startTime) / 1000d;
System.out.println(executionTime);
}
}
,
如果您想知道经过了多少时间,可以使用System.currentMillis()
。而不是将计数器放在秒上。
long startTime = System.currentMillis();
//... your code
long endTime = System.currentMillis();
long timePassed = endTime - startTime;
,
如果要使用second
变量来跟踪从程序启动到用户输入q
的时间。
我建议不要在seconds
中将local
声明为global
。
public class Search {
int seconds = 0; // changed
static public void main(String args[]) throws IOException {
System.out.println("Insert q to stop:");
char i;
i = (char) System.in.read();
do {
seconds++;
} while(i != 'q');
}
}
如果您想阅读是否输入了q
,您可以这样做:
public class Search {
static public void main(String args[]) throws IOException {
int seconds = 0;
System.out.println("Insert q to stop:");
char i;
do {
i = (char) System.in.read(); // changed
seconds++;
} while(i != 'q');
}
}
因为当i = (char) System.in.read()
超出do-while
时,它将仅读取一次,并且如果q
不是输入,它将是一个无限循环。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。