gpt4 book ai didi

java - 如何编码必须包含 3 个或更多字符的字符串值?

转载 作者:行者123 更新时间:2023-12-01 06:11:50 24 4
gpt4 key购买 nike

我试图弄清楚如何限制字符串中使用的字符数量,但是,我似乎无法弄清楚如何编码,例如,如果我说“He”而不是“Hello” ' 我希望我的代码显示错误,因为 'He' 包含的字符少于 3 个。有什么建议么?

package trial;


import java.util.Scanner;

public class Trial {


public static void main(String[] args) {

Scanner input = new Scanner(System.in);


System.out.println("Enter a word: ");
String word = input.nextLine();

System.out.println("The Word you have typed is: " + word);

最佳答案

你的代码很好,只是让用户不断输入值,直到字符超过 3 个,这样你就可以通过 while 循环来检查单词的字符数

package trial;


import java.util.Scanner;

public class Trial {


public static void main(String[] args) {

Scanner input = new Scanner(System.in);

String word="";
while(word.length()<3){

System.out.println("Enter a word with more or equals to 3 characters: ");

word = input.nextLine();
}
System.out.println("The Word you have typed is: " + word);

关于java - 如何编码必须包含 3 个或更多字符的字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32914395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com