Java循环参数被忽略;循环不中断

huangapple go评论68阅读模式
英文:

Java Loop parameters are ignored; Loop doesn't break

问题

我希望我的输入最少是4个字符串最多不超过8个我正在对它们进行分词练习我已经设置了参数使得标记数必须超过4并且少于8但是无论标记数如何我的代码都在运行我不知道为什么

我还尝试在多个位置插入中断但我无法弄清楚如何停止它并继续执行每次运行它时我都需要手动终止它

我想获取输入重新打印它列出每个标记中的字符数然后重新评估字符包括大写/小写数字和空白字符

我真的很感谢任何见解

以下是我的代码

import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;

public class charEvaluation {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        ArrayList<String> tokenizedInput = new ArrayList<>();
        String sentenceRetrieved;

        // 获取用户输入的句子
        System.out.println("请输入包含至少4个单词的句子,最多8个单词:");
        sentenceRetrieved = sc.nextLine();
        StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);

        while (true) {
            while (strTokenizer.hasMoreTokens()) {
                tokenizedInput.add(strTokenizer.nextToken());
            }
            int count = tokenizedInput.size();
            if (count <= 8 && count >= 4) {
                break;
            }
        }

        // 打印句子
        System.out.println("您输入了:");
        System.out.println(sentenceRetrieved);

        // 统计每个单词中的字符数
        int totalLength = 0;

        for (String each : tokenizedInput) {
            totalLength += each.length();
            System.out.println(each + " 包含 " + each.length() + " 个字符。");
        }

        System.out.println("输入的字符总数(不包括空格):" +
                sentenceRetrieved.replace(" ", "").length());

        /*
         * 设置字符数组并确定输入中有多少个字母、数字、小写字母、大写字母和空白字符。
         */

        char[] array;
        int letters = 0,
                digits = 0,
                lowerCase = 0,
                upperCase = 0,
                whitespaces = 0;

        array = sentenceRetrieved.toCharArray();
        for (int i = 0; i < array.length; i++) {
            if (Character.isLetter(array[i]))
                letters++;
            if (Character.isDigit(array[i]))
                digits++;
            else if (Character.isUpperCase(array[i]))
                upperCase++;
            else if (Character.isLowerCase(array[i]))
                lowerCase++;
            else if (Character.isWhitespace(array[i]))
                whitespaces++;
        }

        System.out.println("字母的数量为 " + letters + "。");
        System.out.println("数字的数量为 " + digits + "。");
        System.out.println("小写字母的数量为 " + lowerCase + "。");
        System.out.println("大写字母的数量为 " + upperCase + "。");
        System.out.println("空白字符的数量为 " + whitespaces + "。");

        // 退出循环
        break;
    }
}
英文:

I want my input to be a minimum of 4 strings and a maximum of 8. I am tokenizing them for practice. I have parameters set up so that the number of tokens must be over 4 and less than 8, but my code runs no matter the number of tokens and I don't know why.

I have also tried to insert a break at multiple locations and I cannot figure out how to stop it and continue on. Each time I run it I need to manually terminate it.

I want to get the input, reprint it, list the number of chars in each token, then reevaluate the chars again for upper/lower cases, digits, white spaces.

I really appreciate any insight.

Here is my code:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class charEvaluation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList&lt;String&gt; tokenizedInput = new ArrayList&lt;&gt;();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println(&quot;Please type a sentence containing at least 4 words, with a maximum of 8 words: &quot;);
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
while (true) {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
int count = strTokenizer.countTokens();
if (count &lt;= 8 &amp;&amp; count &gt;= 4) {
break;
}
}
// printing out the sentence
System.out.println(&quot;You entered: &quot;);
System.out.println(sentenceRetrieved);
// count the characters in each word
int totalLength = 0;
for (String each : tokenizedInput) {
totalLength += each.length();
System.out.println( each + &quot; has &quot; + each.length() + &quot; characters.&quot;);
}
System.out.println(&quot;The total number of characters entered without spaces: &quot;+
sentenceRetrieved.replace(&quot; &quot;, &quot;&quot;).length());
/*
* Setting up a character array and determining how many
* letters, digits, lower case letters, upper case letters and white spaces in the input.
*/
char [] array;
int letters = 0,
digits = 0,
lowerCase = 0,
upperCase = 0,		     	
whitespaces = 0;
array = sentenceRetrieved.toCharArray();
for(int i = 0; i&lt; array.length; i++) {
if (Character.isLetter(array[i]))
letters ++;
if(Character.isDigit(array[i]))
digits++;
else if(Character.isUpperCase(array[i]))
upperCase++;
else if(Character.isLowerCase(array[i]))
lowerCase++;
else if(Character.isWhitespace(array[i]))
whitespaces++;
}
System.out.println(&quot;The number of letters is &quot; + letters + &quot;.&quot;);
System.out.println(&quot;The number of digits is &quot; + digits + &quot;.&quot;);
System.out.println(&quot;The number of lower case letters is &quot; + lowerCase+ &quot;.&quot;);
System.out.println(&quot;The number of upper case letters is &quot; + upperCase + &quot;.&quot;);
System.out.println(&quot;The number of white spaces is &quot; + whitespaces + &quot;.&quot;);
}
}
}

My output to console then is a continual loop of the following, before I manually terminate it:

You entered: 
hi there
hi has 2 characters.
there has 5 characters.
The total number of characters entered without spaces: 7
The number of letters is 7.
The number of digits is 0.
The number of lower case letters is 7.
The number of upper case letters is 0.
The number of white spaces is 1.

All of the information is accurate, but I don't want it to accept a count of less than 4 tokens or more than 8 and I then want it to stop after this output is provided once.

I really appreciate any insight.

答案1

得分: 1

问题在于您必须以某种方式停止主循环;修复它的最简单方法是引入一个布尔变量,用于指示应用程序应该终止循环,如下所示:

public static void main(String[] args) {

    ArrayList<String> tokenizedInput = new ArrayList<>();
    String sentenceRetrieved = "";

    boolean isConditionsMet = false;
    while (!isConditionsMet) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
        sentenceRetrieved = sc.nextLine();
        StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
        int count = strTokenizer.countTokens();
        if (count <= 4 || count >= 8) {
            continue;
        } else {
            isConditionsMet = true;
        }

        while (strTokenizer.hasMoreTokens()) {
            tokenizedInput.add(strTokenizer.nextToken());
        }
    }

    // 打印出句子
    System.out.println("You entered: ");
    System.out.println(sentenceRetrieved);

    // 计算每个单词的字符数
    int totalLength = 0;

    for (String each : tokenizedInput) {
        totalLength += each.length();
        System.out.println(each + " has " + each.length() + " characters.");
    }

    System.out.println("The total number of characters entered without spaces: " +
            sentenceRetrieved.replace(" ", "").length());

    /*
     * 设置字符数组并确定输入中的字母、数字、小写字母、大写字母和空格数量。
     */

    char[] array;
    int letters = 0,
            digits = 0,
            lowerCase = 0,
            upperCase = 0,
            whitespaces = 0;

    array = sentenceRetrieved.toCharArray();
    for (int i = 0; i < array.length; i++) {
        if (Character.isLetter(array[i]))
            letters++;
        if (Character.isDigit(array[i]))
            digits++;
        else if (Character.isUpperCase(array[i]))
            upperCase++;
        else if (Character.isLowerCase(array[i]))
            lowerCase++;
        else if (Character.isWhitespace(array[i]))
            whitespaces++;
    }

    System.out.println("The number of letters is " + letters + ".");
    System.out.println("The number of digits is " + digits + ".");
    System.out.println("The number of lower case letters is " + lowerCase + ".");
    System.out.println("The number of upper case letters is " + upperCase + ".");
    System.out.println("The number of white spaces is " + whitespaces + ".");
}

此外,关于您的代码还有一个小注释 - totalLength 从未被使用。

英文:

The issue is that you have to stop your main for loop somehow; the easiest way to fix it is introduce boolean variable that will indicate to the application that loop should be terminated as such:

        public static void main(String[] args) {
ArrayList&lt;String&gt; tokenizedInput = new ArrayList&lt;&gt;();
String sentenceRetrieved = &quot;&quot;;
boolean isConditionsMet = false;
while (!isConditionsMet) {
Scanner sc = new Scanner(System.in);
System.out.println(&quot;Please type a sentence containing at least 4 words, with a maximum of 8 words: &quot;);
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
int count = strTokenizer.countTokens();
if (count &lt;= 4 || count &gt;= 8) {
continue;
} else {
isConditionsMet = true;
}
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
}
// printing out the sentence
System.out.println(&quot;You entered: &quot;);
System.out.println(sentenceRetrieved);
// count the characters in each w
int totalLength = 0;
for (String each : tokenizedInput) {
totalLength += each.length();
System.out.println(each + &quot; has &quot; + each.length() + &quot; characters.&quot;);
}
System.out.println(&quot;The total number of characters entered without spaces: &quot; +
sentenceRetrieved.replace(&quot; &quot;, &quot;&quot;).length());
/*
* Setting up a character array and determining how many
* letters, digits, lower case letters, upper case letters and white spaces in the input.
*/
char[] array;
int letters = 0,
digits = 0,
lowerCase = 0,
upperCase = 0,
whitespaces = 0;
array = sentenceRetrieved.toCharArray();
for (int i = 0; i &lt; array.length; i++) {
if (Character.isLetter(array[i]))
letters++;
if (Character.isDigit(array[i]))
digits++;
else if (Character.isUpperCase(array[i]))
upperCase++;
else if (Character.isLowerCase(array[i]))
lowerCase++;
else if (Character.isWhitespace(array[i]))
whitespaces++;
}
System.out.println(&quot;The number of letters is &quot; + letters + &quot;.&quot;);
System.out.println(&quot;The number of digits is &quot; + digits + &quot;.&quot;);
System.out.println(&quot;The number of lower case letters is &quot; + lowerCase + &quot;.&quot;);
System.out.println(&quot;The number of upper case letters is &quot; + upperCase + &quot;.&quot;);
System.out.println(&quot;The number of white spaces is &quot; + whitespaces + &quot;.&quot;);
}

Also, small note regarding your code - totalLength is never used.

答案2

得分: 0

另一种方法是通过标签对无限外循环进行标记:

// 在此处添加您的标签。
outerLoop:
while (true) {
if (..condition..) {
// 此语句将中断对应标记的循环。
break outerLoop;
}
}
英文:

Another way is marking your infinite outer loop by a label:

// your label here.
outerLoop:
while (true) {
if (..condition..) {
// this statement will break corresponding marked loop.
break outerLoop;
}
}

答案3

得分: -1

请问您正在使用哪个集成开发环境(IDE)?您知道什么是调试器吗?尝试在调试器中运行您的代码。

我认为您的代码是正确的,但据我所见,“while始终为真”。因此它会无限运行。只需创建一个布尔变量,并在结尾处将其设置为false。

if (strTokenizer.countTokens() >= 4 && strTokenizer.countTokens() <= 8) {
    int count = strTokenizer.countTokens();
    System.out.println(count);
} else {
    System.out.println("Error. 请输入包含至少4个单词的句子,最多8个单词。");
    System.exit(1);
}

for (int i = 0; i <= strTokenizer.countTokens(); i++) {
    tokenizedInput.add(i, strTokenizer.nextToken());
}

// 打印出句子
System.out.println("您输入的是:");
System.out.println(sentenceRetrieved);

// 统计每个单词中的字符数
int totalLength = 0;
英文:

Which IDE are you using ? Do you know what a debugger is ?
Try your code in a debugger.

I think your code is correct but as far as I can see "while is always true". So it runs endless. Just create a boolean and set it to false at the end.

if (strTokenizer.countTokens ( ) &gt;= 4 &amp;&amp; strTokenizer.countTokens ( ) &lt;= 8) 
{
int count = strTokenizer.countTokens ( ); 
System.out.println (count); 
} 
else 
{
System.out.println (&quot;Error. Please type a sentence containing at least 4 words, with a maximum of 8 words&quot;); 
System.exit (1); 
}
for (int i = 0; i &lt;= strTokenizer.countTokens ( ); i++) 
{
tokenizedInput.add (i, strTokenizer.nextToken ( ) ); 
}
// printing out the sentence
System.out.println (&quot;You entered: &quot;);
System.out.println (sentenceRetrieved);
// count the characters in each word
int totalLength = 0;

huangapple
  • 本文由 发表于 2020年9月15日 09:29:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63893809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定