标签: while-loop

while循环的示例,不能写为for循环

我知道while循环可以执行任何for循环,但是for循环可以执行任何循环吗?

请举个例子.

loops for-loop while-loop flow-control

6
推荐指数
1
解决办法
3300
查看次数

在Linux中运行时,Java不会破坏一段时间

我发现了一个用于家庭作业的Java代码的神秘问题.一个朋友在开始时编写一个应用程序:

public void run() {
    vm.setVisible(true);
    while(!end);
    System.out.println("Finish");
    vm.setVisible(false);
}
Run Code Online (Sandbox Code Playgroud)

在所有执行时以及当用户退出应用程序时,布尔'end'为false,这种情况发生:

private class CloseSys implements ActionListener {
    public CloseSys() {super();}

        public void actionPerformed(ActionEvent e) {
        System.out.println("CLOSE SYS");
        System.out.println("end: "+end);
        end = true;
        System.out.println("end: "+end);
    }
}
Run Code Online (Sandbox Code Playgroud)

println显示像'end'的值更改为true和逻辑上在我朋友的计算机(MacOS)中完成和应用程序也是如此.

问题是在我的计算机(Ubuntu Linux)中,println也显示了值的变化,但是while没有结束(永远不会达到"Finish"println).有趣的是,如果我们把印刷品放到一边......然后才有效!

java linux while-loop

6
推荐指数
2
解决办法
169
查看次数

如何在C#上的控制台应用程序中停止使用键盘输入的运行方法?

简而言之,我正在利用C#进行科学计算,并且我编写了一个方法,该方法具有可以运行到用户指定数量的步骤的while循环......实际上,这种方法可能需要很长时间才能执行(如更多超过5小时).如果需要这么长时间,我可能想要停止方法Esc按键,例如.

当我读到关于破坏的东西时while,它就像Boolean旗帜或类似的东西一样简单.所以我想到这样的事情:

public Double? Run(int n)
{
    int i = 0;
    while ((i < n) && (/* inputkey != ConsoleKey.Escape */))
    {
        // here goes the heavy computation thing
        // and I need to read some "inputkey" as well to break this loop
        i++;
    }
    // I'm not worried about the return statement, as it is easy to do...
    // returns null if the user skipped the method by pressing Escape
    // returns null …
Run Code Online (Sandbox Code Playgroud)

c# user-input input break while-loop

6
推荐指数
2
解决办法
5749
查看次数

当终止条件依赖于来自不同部分的更新时,为什么OMP并行部分中的while循环无法终止

C++代码是否合法,或者我的编译器有问题吗?代码被编译到一个共享库中使用

gcc版本4.4.6 20110731(Red Hat 4.4.6-3)(GCC)

和openMP然后通过R 2.15.2调用.

int it=0;
#pragma omp parallel sections shared(it)
   {
      #pragma omp section
      {
           std::cout<<"Entering section A"<<std::endl;
           for(it=0;it<10;it++)
           {
                   std::cout<<"Iteration "<<it<<std::endl;

           }
           std::cout<<"Leaving section A with it="<<it<<std::endl;
      }

      #pragma omp section
      {
           std::cout<<"Entering section B with it="<<it<<std::endl;
           while(it<10)
           {
                   1;
           }
           std::cout<<"Leaving section B"<<std::endl;
  }
}
Run Code Online (Sandbox Code Playgroud)

我获得了以下输出(对于从2个线程交织输出的道歉,但我认为它是可解释的):

Entering section A
Iteration Entering section B with it=0
0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
Iteration 8
Iteration 9 …
Run Code Online (Sandbox Code Playgroud)

c++ for-loop openmp while-loop

6
推荐指数
1
解决办法
3019
查看次数

"while()"功能?

该程序应该将华氏度转换为摄氏度:

#include <stdio.h>
int main() {
    float fahrenheit, celsius;
    int max, min, step;

    max = 100;
    min = 0;
    step = 5;

    fahrenheit = 0.0;
    //celsius = (fahrenheit - 32.0) * 5.0/9.0; DOESN'T WORK HERE

    printf("\n");
    printf("This program converts fahrenheit into celsius \n");

    while(fahrenheit <= max) {
        celsius = (fahrenheit - 32.0) * 5.0/9.0; /* Works here */
        printf("%3.0f %6.2f\n", fahrenheit, celsius);
        fahrenheit = fahrenheit + step;
    }
}
Run Code Online (Sandbox Code Playgroud)

正如我在源代码中所提到的那样,当我尝试将摄氏公式放入main()函数体中时,我会得到-17.8每一个华氏值.输出看起来像这样 -

0 -17.78
5 -17.78
10 …
Run Code Online (Sandbox Code Playgroud)

c while-loop

6
推荐指数
1
解决办法
411
查看次数

在大量迭代之后,Java while循环会随着时间的推移而显着减慢

我的程序在while循环中逐行读取文本文件.然后它处理每一行并提取要在输出中写入的一些信息.它在while循环中所做的一切都是O(1),除了两个我认为是O(N)的ArrayList indexOf()方法调用.该程序在开始时以合理的速度运行(每100秒1M行),但随着时间的推移它会大幅减速.我在输入文件中有70 M行,因此循环迭代7000万次.从理论上讲,这应该需要大约2个小时,但实际上需要13个小时.问题出在哪儿?

这是代码片段:

BufferedReader corpus = new BufferedReader(
            new InputStreamReader(
                        new FileInputStream("MyCorpus.txt"),"UTF8"));

Writer outputFile = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream("output.txt"), "UTF-8"));

List<String> words = new ArrayList();
//words is being updated with relevant values here   

LinkedHashMap<String,Integer> DIC = new LinkedHashMap();
//DIC is being updated with relevant key-value pairs here    

String line = ""; 
while ((line = corpus.readLine()) != null)
    String[] parts = line.split(" ");
    if (DIC.containsKey(parts[0]) && DIC.containsKey(parts[1])) {

        int firstIndexPlusOne = words.indexOf(parts[0])+ 1;
        int secondIndexPlusOne = words.indexOf(parts[1]) +1;

        outputFile.write(firstIndexPlusOne …
Run Code Online (Sandbox Code Playgroud)

java time-complexity while-loop

6
推荐指数
1
解决办法
992
查看次数

如果没有正文,Java中的while循环不会检查它们的条件吗?

在这个例子中,我有一个简单的JFrame包含一个绑定了ActionListener的JButton.这个AcitonListener只是更改了一个允许程序完成的布尔标志.

public class Test {
    public static void main(String[] args){
        final boolean[] flag = new boolean[1];
        flag[0] = false;
        JFrame myFrame = new JFrame("Test");
        JButton myButton = new JButton("Click Me!");
        myButton.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("Button was clicked!");
                flag[0] = true;
            }
        });
        myFrame.add(myButton);
        myFrame.setSize(128,128);
        myFrame.setVisible(true);
        System.out.println("Waiting");
        while(!flag[0]){}
        System.out.println("Finished");
    }
}
Run Code Online (Sandbox Code Playgroud)

这永远不会打印"完成",并且在点击按钮后打印一次

Waiting
Button was clicked!
Run Code Online (Sandbox Code Playgroud)

但是,如果我修改while循环来读取

while(!flag[0]){
    System.out.println("I should do nothing. I am just a print statement.");
}
Run Code Online (Sandbox Code Playgroud)

这有效!打印输出看起来像

Waiting
I should do nothing. I am …
Run Code Online (Sandbox Code Playgroud)

java while-loop

6
推荐指数
1
解决办法
302
查看次数

For循环条件约定

我最近讨论了在Java中的for循环中使用非计数器相关条件:

for(int i = 0; o.getC() < 10; i++)
    o.addC(i);
Run Code Online (Sandbox Code Playgroud)

有没有人知道这样的条件是否有任何"官方"约定?在我看来,与等效的while循环相比,它更容易阅读,因为所有循环参数都在第一行中:

int i = 0;
while(o.getC() < 10) {
    i++;
    o.addC(i);
}
Run Code Online (Sandbox Code Playgroud)

甚至更糟:

int i = 0;
while(o.getC() < 10)
    o.addC(++i);
Run Code Online (Sandbox Code Playgroud)

java for-loop conventions while-loop conditional-statements

6
推荐指数
1
解决办法
128
查看次数

是否可以在`while let`中使用模式匹配防护?

我有一个while let循环遍历迭代器Result并使用模式匹配; 它遍历迭代器,直到它命中一个Err或者它Ok的值是一个空字符串:

while let Some(Ok(a)) = some_iterator.next() {
    if a == "" {
        break;
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这段代码工作正常.但是,我认为这个if陈述看起来很难看,可能不是惯用的Rust.在match语句中,保护可以用于模式匹配,如下所示:

match foo {
    Some(Ok(a)) if a != "" => bar(a)
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这对我的while let循环来说是理想的,虽然那里使用的模式匹配似乎不支持它,导致语法错误:

while let Some(Ok(a)) = some_iterator.next() if a != "" { // <-- Syntax error
    // ...
}
Run Code Online (Sandbox Code Playgroud)

在这样的情况下,有没有办法使用这样的守卫while let?如果没有,如果发现空字符串,是否有更好的方法可以打破循环?

pattern-matching while-loop rust

6
推荐指数
1
解决办法
812
查看次数

我在使用嵌套的for循环和String替换函数时遇到了麻烦

public class Hangman {

    public static void ttt(String inputWord) {                          //setting up the game and declaring the secret word to be the input
        int wordLength = inputWord.length();                            //making new integer variable for length of word
        String blanks = "";                                             //creating blanks string
        for(int i = 0; i < wordLength; i++) {                           //making one blank for every letter of the word
            blanks = blanks.concat("_ ");
        }
        System.out.println(blanks);                                     //initially just to show user how many blanks/letters there are to guess
        int points …
Run Code Online (Sandbox Code Playgroud)

java while-loop

6
推荐指数
1
解决办法
120
查看次数