gpt4 book ai didi

Java - 在 Switch Case 中调用另一个输入方法

转载 作者:太空宇宙 更新时间:2023-11-04 06:16:47 26 4
gpt4 key购买 nike

由于我想避免与之前的帖子混淆,因此我正在创建一个新线程。

我希望在案例成功后检索输入。但是,我尝试了在满足 Case 'A' 后检索输入的方法,但没有成功。

感谢您提供的任何帮助。

public class Test {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char choice = getInput(sc);
String result;

switch (choice) {
case ('a'): result = "u choose a";
System.out.println(result);

//I wish to display result from getInputA method here as well.
break;
}
}

private static char getInput(Scanner sc)
{
System.out.println("Enter a");
char choice = sc.nextLine().trim().toLowerCase().charAt(0);

while (choice != 'a')
{
System.out.println("You have entered an invalid entry.");
System.out.println("Enter a");
choice = sc.nextLine().trim().toLowerCase().charAt(0);
}

return choice;

}
private static String getInputA (String inputA)
//***How may I get input from this method in the main method?***
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter your first name: ");
String fName=sc.next();
System.out.print("Enter your last name: ");
String lName=sc.next();

String output=("Your name is: "+fName+ " " +lName);

return output;
}

最佳答案

首先,如果您希望其代码运行,则需要调用您的方法。

第二,最好通过扫描仪而不是创建新的扫描仪。

import java.util.*;

public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char choice = getInput(sc);
String result;

switch (choice) {
case ('a'):
result = "u choose a";
System.out.println(result);

//I wish to display result from getInputA method here as well.
result = getInputA(sc);
System.out.println(result);
break;
}
}

private static char getInput(Scanner sc)
{
System.out.println("Enter a");
char choice = sc.nextLine().trim().toLowerCase().charAt(0);

while (choice != 'a')
{
System.out.println("You have entered an invalid entry.");
System.out.println("Enter a");
choice = sc.nextLine().trim().toLowerCase().charAt(0);
}
return choice;
}
private static String getInputA(Scanner sc)
{
System.out.print("Enter your first name: ");
String fName=sc.next();
System.out.print("Enter your last name: ");
String lName=sc.next();
String output=("Your name is: "+fName+ " " +lName);
return output;
}
}

关于Java - 在 Switch Case 中调用另一个输入方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28002475/

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