作业逻辑错误。奇怪如果声明

时间:2015-10-12 02:37:07

标签: java

我是一名有Java逻辑错误的大学新生。对于此分配,用户应输入1或2以确定是从磅到千克还是从千克到磅(ConversionStatus)。每当我运行程序并输入1或2时,我收到错误消息"无效响应,程序关闭"。

Scanner input = new Scanner(System.in);

// Declarations
double Weight, Pounds, Kilograms;
double ConversionStatus;

// Print Convert weights prompt
System.out.println("Convert Weights: ");
System.out.println("Pounds to Kilograms (enter 1)");
System.out.println("Kilograms to pounds (enter 2)");
System.out.println(" ");
System.out.print("Which conversion do you want? ");
ConversionStatus = input.nextInt();
// If ConversionStatus isnt 1 or 2, print "Invalid response, please restart program"
if (ConversionStatus != 1 || ConversionStatus != 2)
{
  System.out.println("Invalid Response, Program Closing");
  System.exit(3);
}
System.out.print("What weight value do you want converted? ");
Weight = input.nextInt();


// Pounds to Kilograms Program if ConversionStatus=1
if (ConversionStatus == 1)
{
  Pounds = Weight;
  Kilograms = Pounds / 2.2;
  System.out.println(Pounds + "converted to kilograms is: " + Kilograms);
}

2 个答案:

答案 0 :(得分:4)

这将始终为真:

if (ConversionStatus!=1 || ConversionStatus!=2)

因为相同的值永远不能同时等于 1和2.所以这两个语句中至少有一个必须为真。

听起来你只想在两个部分都是真的时调用这个代码,而不仅仅是其中一个:

if (ConversionStatus!=1 && ConversionStatus!=2)

答案 1 :(得分:2)

if (ConversionStatus!=1 || ConversionStatus!=2){

想一想。如果ConversionStatus == 1怎么办?然后同时ConversionStatus != 2,程序将退出。

您想使用&&运算符,而不是||