我现在正在学习Java,但我遇到了问题。在我的场景中,我创建了一系列方法,并要求用户从其中一个方法中进行选择。选择所需方法后,将会有一条消息要求输入字符串或整数。我的问题是在选择了所需的方法后,它跳过第二阶段,要求输入任何字符串/整数。 希望你能理解我的问题。
这是我的简单代码:
import java.util.*;
import java.io.*;
public class MachineProblemChoser {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int chosenProblem;
System.out.println("Choose a problem you want to process");
System.out.println("***********************************************");
System.out.println(" 1 -- Sum of digit");
System.out.println(" 2 -- Days of the month");
System.out.println(" 3 -- Largest number");
System.out.println(" 4 -- Fibonacci");
System.out.println(" 5 -- Palindrome");
System.out.println(" -1 -- Exit");
System.out.println("***********************************************");
System.out.print(" Choose from(1-5) and -1 for exit: ");
chosenProblem = console.nextInt();
String numberSeries;
int inputs;
switch(chosenProblem) {
case 1:
//FROM THIS PART IT SKIPPED THE INPUT FROM THE USER
System.out.println("SUM OF DIGIT");
System.out.println("Input any integer separated by space:");
numberSeries = console.nextLine();
System.out.println("Count is: " + numberSeries.length());
break;
case 2:
//machineProblemTwo();
break;
case 3:
//machineProblemThree();
break;
case 4:
// machineProblemFourth();
break;
case 5:
//machineProblemFifth();
break;
case -1:
exitProgram();
break;
default:
System.out.println(" Oops: Choose a valid number for the selection!");
}
}
public static void machineProblemOne(String chosenNumber) {
System.out.println("Chose number are: " + chosenNumber);
}
public static int validateInput(int inputs) {
return 0;
}
public static void exitProgram() {
System.out.println(" Thanks for using the Machine Problem Choser! ");
}
}
这是输出:
Choose a problem you want to process
***********************************************
1 -- Sum of digit
2 -- Days of the month
3 -- Largest number
4 -- Fibonacci
5 -- Palindrome
-1 -- Exit
***********************************************
Choose from(1-5) and -1 for exit: 1
SUM OF DIGIT
Input any integer separated by space: ---- From this it skipped
Count is: 0
答案 0 :(得分:1)
好吧我测试了你的问题,这可能有用:
尝试替换它:
numberSeries = console.nextLine();
用这个:
numberSeries = System.console().readLine();
这可能会有所帮助。
答案 1 :(得分:1)
scanner.nextInt();从输入中只读取下一个整数。您需要清除剩余的回车。试试这个:
...
System.out.println("***********************************************");
System.out.print(" Choose from(1-5) and -1 for exit: ");
chosenProblem = console.nextInt();
console.nextLine();//this clears out the rest of the input line
String numberSeries;
int inputs;
....