首页 > 解决方案 > 有没有办法获得 System.out.print(); 来自 For 循环的值;

问题描述

我正在猜测字符串程序游戏,我需要将用户输入的字符串从字母和空格/空格转换为问号(?)。我该怎么做呢?

我使用了一个 for 循环,它给了我想要的东西,但我不能在循环外使用 for 循环的输出。

System.out.println("Please enter a string of words.");

        String userString = scan.nextLine();
        userString=userString.toLowerCase();
        System.out.println(userString);

        int s1 = userString.length();
        System.out.println(s1);
        for(int a=0;a<s1;a++) {
            System.out.print("?");
        }

我为 userString 输入了“这是一个字符串”。当我运行程序时,它会输出:???????????????? 有没有办法将此输出转换为字符串?或者有没有更好的方法将字符串值转换为“?”?

标签: javastringfor-loop

解决方案


无需?为每个字符打印。您可以用 a 替换每个字符?并生成一个新字符串而不打印。

String newUserString = userString.replaceAll(".","?");

推荐阅读