gpt4 book ai didi

Java 不会读取我的第二个进程

转载 作者:行者123 更新时间:2023-12-02 04:50:05 25 4
gpt4 key购买 nike

我现在正在学习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

最佳答案

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;
....

关于Java 不会读取我的第二个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29313229/

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