gpt4 book ai didi

java用户输入菜单无法选择选项

转载 作者:行者123 更新时间:2023-11-30 02:40:07 25 4
gpt4 key购买 nike

仍在学校学习Java,但我正在开发一个用户输入选项的程序。 1,2,3,4。问题是我选择的选项之一 oddEvenZero(Option 2) 没有结束。该程序不断要求用户输入一个整数,但不显示结果,也不带回菜单。谢谢。

import java.util.Scanner;

public class IntFun
{
public static void main(String[] args)
{
int option;
int integer;
int evenCount = 0, oddCount = 0, zeroCount = 0;
int optionOne;

Scanner kb = new Scanner(System.in);
System.out.println("Welcome to Integer Fun.");
System.out.println("Please enter a non-negative integer: ");
integer = kb.nextInt();
kb.nextLine();

while((integer < 0))
{
System.out.println("I am sorry that is not a non-negative integer.");
System.out.println("");
System.out.println("Please enter a non-negative integer: ");
integer = kb.nextInt();
}

option = displayMenu(kb);

while (option != 4)
{
switch (option)
{
case 1:
System.out.println("Option 1");
break;
case 2:
optionOne(integer, evenCount, oddCount, zeroCount);
System.out.printf("Even: %d Odd: %d Zero: %d", evenCount, oddCount, zeroCount);
break;
case 3:
System.out.println("Option 3");
break;
}
option = displayMenu(kb);
}
}

private static int displayMenu(Scanner kb)
{
int option = 0;
while (option != 1 && option != 2 && option != 3 && option != 4)
{
System.out.println("\t\t1. Enter a new number\n\t\t2. Print the number of odd digits, even digits and zeros in the integer\n\t\t3. Print the sum of the digits of the integer\n\t\t4. Quit the program");
option = kb.nextInt();
kb.nextLine();
if (!(option == 1 || option == 2 || option == 3 || option == 4))
System.out.println("Invalid choice");
}
return option;
}

private static int optionOne(int integer, int evenCount, int oddCount, int zeroCount)
{
while (integer > 0)
{
integer = integer % 10;
if (integer==0)
{
zeroCount++;
}
else if (integer%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
}
return integer % 10;


}
}

最佳答案

在你的while循环中,你应该一位一位地获取大数的数字。将除法提示记为 10 即可得到号码的最后一位数字。但是你的下一个数字应该不一样,而是这个数字除以 10 的整数部分。此外,你传递给方法的变量在外部将不可用,所以如果你想打印它们 - 直接在你的方法中执行,或者以某种方式返回它们(您很可能需要一些对象)。试试这个:

  private static int optionOne(int integer, int evenCount, int oddCount, int zeroCount)
{
int test = integer;
int temp = test;
do
{
test = temp % 10;
temp = temp / 10;

System.out.println("Current temp number: " + temp);
System.out.println("Current test digit: " + test);
if (test==0)
{
zeroCount++;
}
else if (test%2==0)
{
evenCount++;
}
else
{
oddCount++;
}

} while (temp > 0 );
System.out.printf("Even: %d Odd: %d Zero: %d", evenCount, oddCount, zeroCount);
return integer % 10; // do you really need it?
}

关于java用户输入菜单无法选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42005796/

25 4 0