【问题标题】:How do I save the random generated string to a variable and compute the distance?如何将随机生成的字符串保存到变量并计算距离?
【发布时间】:2020-09-24 21:19:19
【问题描述】:

我正在学习一个 Java 课程,并负责使用这些参数创建一个代码:

(Get String 1 –from user) 提示用户输入一个由 5 个大写字符组成的字符串,并将这个字符串保存在一个变量中。2。

(Get String 2 –randomly generated) 生成一个包含5个随机生成字符的字符串,并保存在一个变量中。

(计算距离)计算两个字符串之间的距离并显示给用户

我想我已经破解了第一个和第二个的一部分,但是在将 string2 保存到变量时遇到了麻烦,而且我似乎无法专注于计算距离。

任何帮助将不胜感激。

这是我目前所拥有的:

import java.util.Scanner;
import java.util.Random;

public class StringDiff {

    public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        
        System.out.println ("Please enter 5 Capital letters.");
        int userString = scan.nextInt();
        
        Math.random().toString(255).substr(2, 5);           
    }
}

【问题讨论】:

  • int userString = scan.nextInt(); 确实 not 读取字符串,你想要 nextLine() 代替。
  • 如何定义字符串距离
  • 谢谢你,托马斯

标签: java string variables random distance


【解决方案1】:

首先:使用 nextLine();插入 nextInt();

第二:要创建一个随机变量,使用这个

1 导入此类

        import java.util.concurrent.ThreadLocalRandom;

2 创建并初始化变量

        int Random_number = ThreadLocalRandom.current().nextInt("Here put the maximum number");

【讨论】:

  • 谢谢!这也适用于字母吗?我需要一个随机字符。我认为意思是字母和数字。
  • 那么喜欢这样吗?
  • int userString = scan.nextLine();
  • int randString = ThreadLocalRandom.current().nextInt(5)
  • 您可以尝试创建一个随机数并为每个字母使用一个开关大小写,例如 1 = a、2 = b、3 = c、4 = d,您可以尝试所有字母的宽度的字母表。或者你可以试试这个geeksforgeeks.org/generate-random-string-of-given-size-in-java
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
相关资源
最近更新 更多