显示带有隐藏字符的字符串

时间:2015-02-23 01:02:45

标签: java arrays string char

我测试了一个显示从数组中随机选择的单词的类。

我正在尝试显示隐藏了几个字符的单词

我已经接受了字符串,然后将其转换为字符数组,但我很困惑从哪里开始。

import java.util.Scanner;
public class wordTest {
    public static void main (String args[])
    {
        Scanner scanner = new Scanner(System.in);
        String readString = scanner.nextLine();
         char[] stringArray;


         String [] gamewords = { "dog", "cat", "coffee", "tag", "godzilla", "gamera", "lightning", "flash", "spoon", "steak", "moonshine", "whiskey", "tango", "foxtrot", "ganymede" 
                 , "saturn", "enterprise", "reliant", "defiant", "doom", "galapagos", "jidai", "sengoku"};

        arrayWords wl = new arrayWords();
     // Words w = new Words();
        Word n = new Word();


    int a = 0;
        int b = gamewords.length;


        RandNum rand = new RandNum(a,b);
        n.setWord(gamewords[rand.nextRandomIntegerInRange()]);

        stringArray = n.getWord().toCharArray();
        int blank1 = 1;
        int blank2 = 4; 

        RandNum blanks = new RandNum(blank1,blank2);



        n.setWord(gamewords[rand.nextRandomIntegerInRange()]);


            do{

                int i = 0;
                //scanner.nextLine();
                  for( i = 0; i < stringArray.length; i++){
                      for( i = 0 ; i < blanks.nextRandomIntegerInRange() ; i++ ){

                          stringArray[i] = '*';
                      }
                          System.out.println(stringArray[i]);

                      }


             }while(scanner.nextLine().equals(""));


    }


    }

2 个答案:

答案 0 :(得分:0)

由于你没有明确定义你想做什么,这里我假设每个字符串,你随机屏蔽2个字符,在伪代码中,它看起来像:

if inputString.length < 2 {
    mask all character
} else {
    loop until 2 character masked {
        r = random from 0 to inputString.length-1
        if (inputString[r] is not masked) {
            set inputString[r] to mask character
        }
    }
}

一些提示:

  1. 使“inputString”可修改,使用StringBuilder
  2. 检查某个位置是否被屏蔽的方法,您可以简单地检查字符串中的字符是否= =掩码字符,或者您可以使用Set来保留所有屏蔽位置
  3. 为了找出蒙面的位置数量,您可以保留一个计数器,或者如果您选择使用套装,只需使用Set的大小。

答案 1 :(得分:0)

好的,所以我认为我找到了解决方案:

for (int i = 0; i < stringArray.length ; i++) {
    stringArray[blanks.nextRandomIntegerInRange()] = '_';
    System.out.print(stringArray[i] + " " );
}