首页 > 解决方案 > 我编译了我的java程序并在eclipse平台上运行,还提供输入但没有得到输出?程序有任何逻辑错误

问题描述

这是基于选择的 Java 程序。因此,在这些程序中,用户必须将 Vegetarian 提供为 V,将 Non-Vegetarian 提供为 N,数量和距离将采用整数值。因此,当我保存并运行程序时,它采用用户参数的值但没有打印输出,我还在 Eclipse 编辑器中检查了错误。

#程序

'''

package demo;
import java.util.Scanner;

public class FoodCorner {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int vegCombo = 12;
        int nonvegCombo = 15;
        int totalCost = 0;
        int charge = 0;
        
        System.out.println("Enter the type of Food Item as Vegeterian 'V' and for Non-Vegeterian as 'N'");
        String foodType = scan.nextLine();
        System.out.println("Enter the Quantity of food Item");
        int quantity = scan.nextInt();
        System.out.println("Enter the Distance for delivery");
        float distance = scan.nextFloat();
        
        while(distance > 3) {
            charge++;
            distance = distance - 3;
        }
        
        if(distance > 0 && quantity >= 1) {         
            if(foodType == "V") {
                totalCost = (vegCombo * quantity) + charge;
                System.out.println("The total cost of your order is: "+totalCost);
            }
            else if(foodType == "N") {
                totalCost = (nonvegCombo * quantity) + charge;
                System.out.println("The total cost of your order is: "+totalCost);
            }
        }
        
        else {
            System.out.println("the bill amount is -1");
        }
        
    }
}

''' java程序的输出

标签: javajava.util.scannerselection

解决方案


使用下面的代码片段。注意 if("V".equals(foodType)) 行而不是 if(foodType == "V")。

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int vegCombo = 12;
        int nonvegCombo = 15;
        int totalCost = 0;
        int charge = 0;

        System.out.println("Enter the type of Food Item as Vegeterian 'V' and for Non-Vegeterian as 'N'");
        String foodType = scan.nextLine();
        System.out.println("Enter the Quantity of food Item");
        int quantity = scan.nextInt();
        System.out.println("Enter the Distance for delivery");
        float distance = scan.nextFloat();

        while(distance > 3) {
            charge++;
            distance = distance - 3;
        }

        if(distance > 0 && quantity >= 1) {
            if("V".equals(foodType)) {
                totalCost = (vegCombo * quantity) + charge;
                System.out.println("The total cost of your order is: "+totalCost);
            }
            else if("N".equals(foodType)) {
                totalCost = (nonvegCombo * quantity) + charge;
                System.out.println("The total cost of your order is: "+totalCost);
            }
        }

        else {
            System.out.println("the bill amount is -1");
        }

    }

推荐阅读