由于我想避免与之前的帖子混淆,我正在创建一个新帖子。
我希望在Case成功后检索输入。但是,在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;
}
答案 0 :(得分:1)
首先,如果您希望运行代码,则需要调用方法。
其次,最好通过扫描仪而不是创建一个新扫描仪。
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;
}
}