java - 我想从循环中输出一次
问题描述
所以我有一个输出无限数组的代码,所以我想检查该数组的值是否低于 80。它按我的意愿打印出来,但它一直打印出来
这是我的代码:
package com.example.testtingskripsi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
import java.util.Timer;
public class MainActivity extends AppCompatActivity {
public TextView mViewLabel;
boolean continueThread = true;
int count =0;
Thread t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewLabel = (TextView) findViewById(R.id.textChanger);
ArrayList<Integer> lst = new ArrayList<Integer>();
Timer j = new java.util.Timer();
t = new Thread(){
@Override
public void run() {
if (continueThread) {
while (continueThread) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
lst.add(70);
lst.add(71);
lst.add(72);
lst.add(73);
lst.add(74);
lst.add(75);
Collections.shuffle(lst);
mViewLabel.setText(String.valueOf(lst.get(count)));
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
j.schedule(
new java.util.TimerTask() {
@Override
public void run() {
if(lst.get(count) < 80){
System.out.println("Ok");
}
}
},
5000
);
count++;
}
}
}
};
}
public void BtnStart(View view){
t.start();
}
public void BtnStop(View view){
continueThread=false;
}
}
如您所见,我知道它在循环中,但我想从数组中检查它是否不在循环中,它会出错。所以我只想打印出“Ok”这样任何人都可以帮我解决它吗?
解决方案
尝试这个 :
t = new Thread(){
@Override
public void run() {
if (continueThread) {
while (continueThread) {
lst.add(70);
lst.add(71);
lst.add(72);
lst.add(73);
lst.add(74);
lst.add(75);
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
Collections.shuffle(lst);
mViewLabel.setText(String.valueOf(lst.get(count)));
}
});
}catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
}
};
j.schedule(
new java.util.TimerTask() {
@Override
public void run() {
while(continueThread){
if(lst.get(count) < 80){
System.out.println("Ok");
break;
}
count++;
}
}
},
5000
);
推荐阅读
- php - 从文件扩展名中获取 MIME 类型并将它们显示在刀片视图上
- rest - 如何在主题自定义的字段中使用 WP REST API 在 wordpress 上发布?
- excel - Excel 中是否可以有多个条件自定义格式?
- c++ - 后增量和前增量
- amazon-web-services - AWS Congito 用户注册超时
- jquery - 如何删除进度条的验证以保存功能
- c - 知道数字是有符号还是无符号只是编译器关注的问题吗?
- android - Android Studio 错误“找不到 android.arch.navigation:navigation-fragment-ktx:2.3.5”
- node.js - NPM 版本未降级
- javascript - 循环中的对象,它不会增加吗?