java—如何让输出打印在同一行上而不重复?

aelbi1ox  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(551)

这是我的密码。它是为课堂设计的,应该通过随机替换“dbqp”来模拟“诵读困难症”。

import java.util.Scanner;

public class Dyslexia
{
  public static void main(String[] args)
  {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a String");
    String str = scanner.nextLine();
    String output = "";

    String e = null;

    for (int i = 0; i < str.length(); i++)
    {
      int randomInt = (int)(Math.random() * 4) + 1; 
      System.out.println(randomInt);

      if (randomInt == 1)
      {
        e = "d";
      }
      if (randomInt == 2)
      {
        e = "b";
      }
      if (randomInt == 3)
      {
        e = "q";
      }
      if (randomInt == 4)
      {
        e = "p";
      }
      output = str.replaceAll("[dbqp]", e);
      System.out.println(output); 
    }
  }
}

我当前得到的输出(假设我输入了qpdb)是:

1
dddd
3
qqqq
3
qqqq
3
qqqq

忽略用于调试的数字,但考虑到这些随机数字,我的目标输出是:

1
d
3
q
3
q
3
q
mfpqipee

mfpqipee1#

你在做一个 replaceAll 调用,只会将它们设置为相同的值。如果希望每个字符单独考虑,则需要为每个字符随机计算和选择,然后用它重新生成一个新字符串。

import java.util.List;
import java.util.Random;

public class DyslexiaExample
{
  public static void main(String[] args) {
    System.out.println(simulateDyslexia("Some possible bountiful quotes."));
  }

  public static String simulateDyslexia(String sentence) {
    List<Character> vals = List.of('d', 'b', 'q', 'p');
    StringBuilder builder = new StringBuilder();

    Random random = new Random();

    for(char c : sentence.toCharArray()) {
      if(vals.contains(c)) {
        builder.append(vals.get(random.nextInt(vals.size())));
      }
      else {
        builder.append(c);
      }
    }

    return builder.toString();
  }
}

样本输出: Some bossible dountiful buotes. 如果您想在哪个字母与另一个字母交换之间保持一致,那么可以考虑生成一个Map。

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DyslexiaExample
{
  public static void main(String[] args) {
    System.out.println(simulateDyslexia("And quite possibly even more boisterous bountiful quotes."));
  }

  public static String simulateDyslexia(String sentence) {
    List<Character> vals = List.of('d', 'b', 'q', 'p');
    StringBuilder builder = new StringBuilder();

    List<Character> shuffleVals = new ArrayList<>(vals);
    Collections.shuffle(shuffleVals);

    Map<Character, Character> swapMap = new HashMap<>();
    for(int i = 0; i < vals.size(); i++)
      swapMap.put(vals.get(i), shuffleVals.get(i));

    for(char c : sentence.toCharArray()) {
      if(swapMap.keySet().contains(c)) {
        builder.append(swapMap.get(c));
      }
      else {
        builder.append(c);
      }
    }

    return builder.toString();
  }
}

样本输出: Anb puite dossiqly even more qoisterous qountiful puotes.

相关问题