如何在不使用break函数的情况下结束以下循环?

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

How to end the following loop without using the break function?

问题

以下是修改后的 Java 程序,它将根据用户输入对字符串进行操作,用户将决定哪个字符需要替换为另一个字符,只替换字符串的第一个字符。例如,如果用户输入字符串 "PUMP" 并决定将 "P" 替换为 "L",则程序应输出以下结果:"LUMP"(注意只有第一个 "P" 被替换为 "L")

注意:不可以使用 BREAK 命令来停止循环。被禁止使用。

以下是修改后的代码:

import java.util.Scanner;

public class StringFun {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter the string to be manipulated");
        String inString = keyboard.nextLine();
        String outString = "";

        // Replace the first character from the string entered by the user only
        System.out.println("Enter the character to replace");
        char oldCharF = keyboard.next().charAt(0);

        System.out.println("Enter the new character");
        char newCharF = keyboard.next().charAt(0);

        boolean replacementDone = false; // Flag to track if replacement is done

        for (int index = 0; index < inString.length(); index++) {
            if (inString.charAt(index) == oldCharF && !replacementDone) {
                outString = outString + newCharF;
                replacementDone = true; // Mark replacement as done
            } else {
                outString = outString + inString.charAt(index);
            }
        }

        System.out.print("The new sentence is: " + outString);

    }

}

你可以使用这个修改后的代码来实现只替换字符串的第一个字符,不再继续替换后续相同字符。

英文:

The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the first character from the string should be replaced. For example, if the user enters the string "PUMP" and decides to replace "P" with "L", the program should output the following result: "LUMP" (notice that only the first "P" was replaced with "L")

NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.

I have written the following program and I am not able to stop at replacing just the first character of the string:

import java.util.Scanner;
public class StringFun {

	public static void main(String[] args) {
		Scanner keyboard = new Scanner(System.in);
		
		System.out.println(&quot;Enter the string to be manipulated&quot;);
		String inString = keyboard.nextLine();
		String outString = &quot;&quot;;
		
		//Replace the first character from the string entered by the user only
		System.out.println(&quot;Enter the character to replace&quot;);
		char oldCharF = keyboard.next().charAt(0);
		
		System.out.println(&quot;Enter the new character&quot;);
		char newCharF = keyboard.next().charAt(0);
		
		
		for(int index = 0;index &lt; inString.length();index++) {
			if(inString.charAt(index) == oldCharF){
				outString = outString + newCharF;
				
			}
			else {
				outString = outString + inString.charAt(index);
			}
			
		}

		System.out.print(&quot;The new sentence is: &quot;+outString);
		

	}

}

I keep getting this result from the above code:

Enter the string to be manipulated

PUMP

Enter the character to replace

P

Enter the new character

L

The new sentence is: LUML

答案1

得分: 2

这可以通过添加计数器来实现,以便跟踪遇到要更改的字母的次数。因为您正在寻找字母的第一次出现,并且只想要更改一个字母,您可以这样做:

  • 添加一个名为count的整数变量,并将其初始化为0。
  • 通过添加"&& counter < 0"来更改for循环中的if条件。
  • 在相同的if条件体内添加"count++"。

这将在第一次遇到要更改的字母时增加计数变量。因为count现在等于1,它将阻止其他任何字母的更改,并解决您之前遇到的问题。

import java.util.Scanner;
public class StringFun {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        
        System.out.println("输入要操作的字符串");
        String inString = keyboard.nextLine();
        String outString = "";
        int count = 0; // 用于跟踪字母出现的次数
        
        // 仅替换用户输入的字符串中的第一个字符
        System.out.println("输入要替换的字符");
        char oldCharF = keyboard.next().charAt(0);
        
        System.out.println("输入新字符");
        char newCharF = keyboard.next().charAt(0);
        
        
        for(int index = 0;index < inString.length();index++) 
        {
            if(inString.charAt(index) == oldCharF && count < 1) // 条件过滤 
            {
                outString = outString + newCharF;
                count++; // 增加计数器
                
            }
            else
                outString = outString + inString.charAt(index);
  
        System.out.print("新句子是:" + outString);
    }
}
英文:

One of the simplest ways to do this is by adding a counter to keep track of how many times the letter you want to change is encountered. Because your looking for the first occurrence of the letter, and only want one letter to change, you could do this:

  • Add an integer variable named count and instantiate it to 0.
  • Change the if condition in the for loop by adding "&& counter < 0"
  • Add "count++" inside the body of the that same if condition.

This will increment the count variable on the first occurrence that the letter being changed has been encountered. Because count will now be equal to 1, it will restrict any other letters from being changed and will solve the issue you had before.

import java.util.Scanner;
public class StringFun {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        
        System.out.println(&quot;Enter the string to be manipulated&quot;);
        String inString = keyboard.nextLine();
        String outString = &quot;&quot;;
        int count = 0; // variable that tracks number of letter occurrences
        
        //Replace the first character from the string entered by the user only
        System.out.println(&quot;Enter the character to replace&quot;);
        char oldCharF = keyboard.next().charAt(0);
        
        System.out.println(&quot;Enter the new character&quot;);
        char newCharF = keyboard.next().charAt(0);
        
        
        for(int index = 0;index &lt; inString.length();index++) 
        {
            if(inString.charAt(index) == oldCharF &amp;&amp; count &lt; 1) //Condition filter 
            {
                outString = outString + newCharF;
                count++; //Increment counter
                
            }
            else
                outString = outString + inString.charAt(index);
  
        System.out.print(&quot;The new sentence is: &quot;+outString);
    }
}

答案2

得分: 2

不过实际上您并不需要在代码中使用 break;。如果您想在不使用 break; 语句的情况下结束您的 for 循环,您只需要使用一个布尔标志来指示是否已找到并处理了要替换的第一个字符,例如:

String inString = "PUMP";
char oldCharF = 'P';
char newCharF = 'L';
String outString = "";

boolean charFound = false;
for (int index = 0; index < inString.length(); index++) {
    char inChar = inString.charAt(index);
    /* 当前字符(inChar)是否是我们正在寻找的字符(oldCharF),并且(&&)它是否尚未被找到(!charFound)? */
    if (inChar == oldCharF && !charFound) {
        // 是的,这就是我们想要的字符
        outString += newCharF;  // 将替代字符附加到 outString。
        charFound = true;       // 将标志更改为 true。
    }
    /* 不,这不是我们想要的字符,或者所需的字符已经被处理过了。 */
    else {
        outString += inChar;
    }
}

// 在控制台窗口中显示 outString 中的结果...
System.out.println(outString);
英文:

Not that you actually want a break; in your code anyways, to end your for loop without utilizing the break; statement all you need to do is utilize a boolean flag to indicate that the first character that is to be replaced has been found and processed, for example:

String inString = &quot;PUMP&quot;;
char oldCharF = &#39;P&#39;;
char newCharF = &#39;L&#39;;
String outString = &quot;&quot;;
    
boolean charFound = false;
for (int index = 0; index &lt; inString.length(); index++) {
    char inChar = inString.charAt(index);
    /* Is the current character (inChar) what we&#39;re 
       looking for (oldCharF) AND (&amp;&amp;) is it NOT 
       found yet (!charFound)?       */
    if (inChar == oldCharF &amp;&amp; !charFound) {
        // Yes, it&#39;s the one we want
        outString += newCharF;  // Append our alternate character to outString.
        charFound = true;       // Change flag to true.
    }
    /* No, it&#39;s not the character we want OR 
       the desired character has already been 
       processed.               */
    else {
        outString += inChar;
    }
}

// Display the result held in outString to Console Window...
System.out.println(outString);

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

发表评论

匿名网友

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

确定