为什么我的Rust程序总是进入while循环而从不退出



我正在通读《铁锈》一书,并在这一过程中进行了最佳练习。我已经完成了第8章(常用集合(,正在尝试最后一个练习。练习说明如下:

使用哈希图和向量创建一个文本界面,允许用户将员工姓名添加到公司的部门。例如,"将Sally添加到工程部门"或"将Amir添加到销售部门"。然后让用户按字母顺序检索一个部门中所有人员或公司中所有人员的列表。

我希望我的程序首先询问用户是否要添加新员工,如果不想,程序结束,否则它允许他们继续添加员工,直到用户拒绝再添加为止。

我选择简单地从最初的用户提示开始,询问他们是否想添加新员工。我从用户输入的空String开始,一旦用户输入他们的响应,就会有一个while循环重复,直到用户输入有效的响应([Y/n](。由于while循环的条件是当响应不等于"y""n"时,我期望正确的响应跳过while循环,但不管怎样,while循环总是被输入且从未退出。由于我是Rust的新手,我不确定这种行为是否有明显或特殊的原因。我还将添加从响应中删除空白(包括n(,并在while循环条件中使响应小写,所有这些都可以在下面的代码中看到。

use std::collections::{HashMap, HashSet};
use std::io;
const DEPARTMENT: [&str; 5] = ["Engineering", "IT", "Sales", "Marketing", "HR"];
fn main() {
// Initialize company roster
let mut company: HashMap<String, HashSet<String>> = HashMap::new();
for key in DEPARTMENT.iter() {
company.insert((*key).to_string(), HashSet::new());
}
// println!("{:?}", company);
let mut response = String::new();
// Prompt user to add a new employee or not
print!("Would you like to add an employee to the company roster? [Y/n] ");
io::stdin().read_line(&mut response).expect("Failed to read line.");
remove_whitespace(&mut response);
// Ensure response is valid
while response.to_lowercase() != "y" || response.to_lowercase() != "n" {
response.drain(..);
println!();
print!("Please respond to the previous question with either 'y' or 'n' (case insensitive): ");
io::stdin().read_line(&mut response).expect("Failed to read line.");
remove_whitespace(&mut response);
// print!("n{}", response.to_lowercase() == "y" || response.to_lowercase() == "n");
}
}
fn remove_whitespace(s: &mut String) {
s.retain(|c| !c.is_whitespace());
}

我很感激任何帮助,帮助我理解为什么这个项目没有达到我的预期。

检查while条件(它总是正确的(,以及您编写的内容

"循环是当响应不等于"0"时;y";或";n〃">

伪码中的手段

NOT(答案="y"或答案="n"(

最新更新