gpt4 book ai didi

java - 如何创建这个循环,使输出与输入相同,除非我按 "end"然后程序结束?

转载 作者:行者123 更新时间:2023-12-01 18:41:59 25 4
gpt4 key购买 nike

嗨,我是java编程新手,我有这段代码,我想知道如何让它运行,直到我输入“end”然后它停止。有人可以帮忙吗?我不断收到错误

public static void main(String [] args){

String code_trigger_starter_str = "start";
String code_trigger_ender_str = "end";
//boolean program_running_bool = false;

Scanner kybd_inpt = new Scanner(System.in);
String kybd_input_str = kybd_inpt.nextLine();


re_run_word_input(code_trigger_starter_str,code_trigger_ender_str);

// exit_code(code_trigger_ender_str);

}


private static void re_run_word_input(String code_trigger_starter_str,String code_trigger_ender_str) {
//boolean program_running_bool = true;

System.out.println("Enter a word");
Scanner kybd = new Scanner(System.in);
String kybd_new_word = kybd.nextLine();


//if(kybd_input_str.equals(code_trigger_starter_str));{

//System.out.println(kybd_new_word);


if(!kybd_new_word.equals(code_trigger_ender_str)) {
System.out.println(kybd_new_word);
}
else {
if (kybd_new_word.equals(code_trigger_ender_str)) {

System.out.println("Program ended");
}
}
}

最佳答案

我找到了一个有效的解决方案。我使用了 do while 循环。

导入java.util.Scanner;

公开课 WeekendAssignment{

public static void main(String [] args){

//Initialize start and end variables
String code_trigger_starter_str = "start";
String code_trigger_ender_str = "end";

// receive start input in string kybd_input_str
Scanner kybd_inpt = new Scanner(System.in);
String kybd_input_str = kybd_inpt.nextLine();


//using do-while loop to run the method continuously
do {
re_run_word_input(code_trigger_starter_str,code_trigger_ender_str);
}
while (true);


}

//create a new method to receive new words input and output the new word
private static void re_run_word_input(String code_trigger_starter_str,String code_trigger_ender_str) {

//Tell user to input a word
System.out.println("Enter a word");
Scanner kybd = new Scanner(System.in);
String kybd_new_word = kybd.nextLine();

//set condition using if and else statements

if(!kybd_new_word.equals(code_trigger_ender_str)) {
System.out.println(kybd_new_word);
}
else {// if user inputs "end" code has to terminate
if (kybd_new_word.equals(code_trigger_ender_str)) {

System.out.println("Program ended");
System.exit(0);


}

}

关于java - 如何创建这个循环,使输出与输入相同,除非我按 "end"然后程序结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59915256/

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