提问人:Rachel Hildebrand 提问时间:5/20/2022 最后编辑:paulsm4Rachel Hildebrand 更新时间:5/20/2022 访问量:446
如何编写一个 Java 程序,从键盘上读取两个代表密码的单词,并在较小的一个中输出字符数?
How do I write a Java program that reads two words representing passwords from the keyboard and outputs the number of characters in the smaller one?
问:
我是学习 Java 的新手,我目前正在编写一个简短的程序,从键盘上输入两个单词并输出较小单词的长度。
我不确定如何做到这一点,因为我不知道用户会提前在键盘上输入什么单词。到目前为止,我已经提示用户编写两个单词并将两个字符串存储在两个单独的变量中。我还创建了另外两个变量来存储两个单词的长度,但是如果我不知道这两个单词是什么,我就不知道如何输出较小的单词。
{
{
Scanner keyboard = new Scanner(System.in);
// Password #1:
System.out.print("Write a word: ");
String passwordOne = keyboard.nextLine();
int passwordLengthOne = passwordOne.length();
// Password #2:
System.out.print("Write another word: ");
String passwordTwo = keyboard.nextLine();
int passwordLengthTwo = passwordTwo.length();
System.out.print("The number of characters in the shorter password is " +
(I have not completed this variable yet) + ".");
}
}
答:
1赞
ferakp
5/20/2022
#1
有很多方法可以做到这一点。这是最简单的一个。
String shorter = "";
if(passwordLengthOne > passwordLengthTwo)
shorter = passwordTwo;
else if(passwordLengthOne < passwordLengthTwo)
shorter = passwordOne;
System.out.print("The shorter password is " + shorter + ".");
System.out.print("The number of characters in the shorter password is " + shorter.length() + ".");
请记住要考虑两者可能具有相同长度的情况。
评论
1赞
Rachel Hildebrand
5/20/2022
谢谢!我还没有在我的教科书中了解 if else 语句,但这解决了我的问题,谢谢。
1赞
paulsm4
5/20/2022
注意:您可能还应该处理 paswordLength1 == passwordLength2 的情况
0赞
Rachel Hildebrand
5/21/2022
如果两个密码匹配,我是否应该打印一条消息,要求用户写一个不同的单词?
评论