我无法从驱动程序中运行下面的菜单。该程序将执行,但在我输入数字之前它不会显示我的菜单。之后它将正确显示,并正确读取选择,但不会调用我在 case 语句中列出的方法。
例如,如果我输入“1”,菜单将识别出我输入了“1”,并再次显示菜单“您输入了 1”。而不是根据 case 语句调用 dec.getDec() 。任何有用的提示或建议将不胜感激。这是一项家庭作业,我并不是想让别人为我编写代码或任何东西。我只需要指出正确的方向。
import java.io.IOException;
import java.io.*;
import java.util.Scanner;
public class Menu {
Scanner scan = new Scanner(System.in);
int selection;
public int GetSelection()
{
selection = scan.nextInt();
return selection;
}
public void display()
{
System.out.println("Please choose an option from the following:");
System.out.println("[1] Convert Decimal to Binary");
System.out.println("[2] Convert Decimal to Hexadecimal");
System.out.println("[3] Convert Binary to Decimal");
System.out.println("[4] Convert Binary to Hexadecimal");
System.out.println("[5] Convert Hexadecimal to Decimal");
System.out.println("[6] Convert Hexadecimal to Binary");
System.out.println("[0] Exit");
System.out.println("\n");
System.out.println("You entered: " + selection);
}
}
----------------------------
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)throws IOException {
LineWriter lw = new LineWriter("csis.txt");
int selection;
Decimal dec = new Decimal();
Binary bin = new Binary();
Hexadecimal hex = new Hexadecimal();
Menu menu = new Menu();
do{
menu.display();
selection=menu.GetSelection();
switch (selection){
case '1':{ dec.getDec();
break;}
case '2':{ dec.getHex();
break;}
case '3':{ bin.getBin();
break;}
case '4':{ bin.getHex();
break;}
case '5':{ hex.getHex();
break;}
case '6': { hex.getDec();
break; }
//default: System.out.println("Error: Unrecognized Selection");
// break;
}
}while (selection !=0);
}
}
最佳答案
由于这是家庭作业,我不会给你完整的解决方案,但我会帮助你实现......
您的问题来自于您使用Scanner ,此页面的有用部分是扫描操作可能会阻塞等待输入。
使用它,您应该能够看到问题出在哪里,如果您需要更多帮助,请对此答案发表评论,我会看看是否还有更多我可以做的。
关于Java:Switch 语句未正确调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12357780/