我无法弄清楚我的简单Java作业

时间:2010-10-03 05:34:21

标签: java

我有这个编程任务,可以在米和英尺之间,以及千克到磅之间进行转换。当我告诉程序我想要转换重量时(通过在提示时输入“w”),它给了我以下错误:

  

Error: Too many input characters error.

我在这方面工作了很长时间,但无法理解。有人可以告诉我如何使重量转换像长度转换一样工作吗?

import java.util.Scanner;

/**
 * This class..
 */
public class UnitConversion3b
{
    public static void main(String[] args)   
    {
        Scanner keyboard = new Scanner(System.in);

        String maxInputWarning = "\nError: Too many input characters."
        + "\nProgram is now terminating.";
        String lengthOrWeight;
        final double LENGTH_CONVERSION_FACTOR = 3.2808399;
        final double WEIGHT_CONVERSION_FACTOR = 2.20462;
        String whichWeightConversion = "empty" , whichLengthConversion = "empty";
        double feet = 0, meters = 0, pounds =0 , kilograms = 0;
        double metersConvertedToFeet, feetConvertedToMeters;
        double poundsConvertedToKilograms, kilogramsConvertedToPounds;

        System.out.println("");
        System.out.print("What kind of value would you like to convert?");
        System.out.print("\nEnter L for length, or W for weight: ");
        lengthOrWeight = keyboard.nextLine();
        if (lengthOrWeight.length() > 1 ) {
            System.out.println(maxInputWarning);
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        } else if ((!(lengthOrWeight.equalsIgnoreCase("l"))
            && (!(lengthOrWeight.equalsIgnoreCase("w"))))){
            System.out.println("\nError: Unrecognized conversion type."
            + "\nProgram is now terminating.");
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        } else if (lengthOrWeight.equalsIgnoreCase("l")){
            System.out.println("\nConverting feet or meters?");
            System.out.print("Enter F to convert feet, or M for meters: "); 
            whichLengthConversion = keyboard.nextLine();
        }

        if (whichLengthConversion.length() > 1 ) {
            System.out.println(maxInputWarning);
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        } else if ((!(whichLengthConversion.equalsIgnoreCase("f"))
            && (!(whichLengthConversion.equalsIgnoreCase("m"))))){
            System.out.println("\nError: Unrecognized unit of "
            + "measurement.\nProgram is now terminating."     );
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        } else if (whichLengthConversion.equalsIgnoreCase("f")){
            System.out.print ("Enter the number of feet to"
            + " convert to meters: ");
            feet = keyboard.nextDouble();
            feetConvertedToMeters = feet / LENGTH_CONVERSION_FACTOR;
            System.out.println("The number of meters in " + feet +
            " feet is " + feetConvertedToMeters + ".");
            keyboard.nextLine();
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        } else if (whichLengthConversion.equalsIgnoreCase("m")){
            System.out.print ("Enter the number of meters to"
            + " convert to feet: ");
            meters = keyboard.nextDouble();
            metersConvertedToFeet = meters * LENGTH_CONVERSION_FACTOR;
            System.out.println("The number of feet in " + meters +
            " meters is " + metersConvertedToFeet + ".");
            keyboard.nextLine();
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        }

        if (lengthOrWeight.equalsIgnoreCase("w")){
            System.out.println("Converting pounds or kilograms?");
            System.out.print("Enter P to convert pounds, or K for kilograms: ");
            whichWeightConversion = keyboard.nextLine();
        }

        if (whichWeightConversion.length() > 1 ) { 
            System.out.println(maxInputWarning);
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        } else if ((!(whichWeightConversion.equalsIgnoreCase("p"))
            && (!(whichWeightConversion.equalsIgnoreCase("k"))))){
            System.out.println("\nError: Unrecognized unit of "
            + "measurement.\nProgram is now terminating."     );
            System.out.print("Press Enter to continue ... ");
            return;
        } else if (whichWeightConversion.equalsIgnoreCase("p")){
            System.out.println("Enter the number of pounds to"
            + " convert to kilograms:");
            pounds = keyboard.nextDouble();
            poundsConvertedToKilograms = pounds / WEIGHT_CONVERSION_FACTOR;
            System.out.println("The number of pounds in " + kilograms +
            " kilograms is " + poundsConvertedToKilograms + ".");
            keyboard.nextLine();
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        } else if (whichLengthConversion.equalsIgnoreCase("k")){
            System.out.print ("Enter the number of kilograms to"
            + " convert to pounds: ");
            kilograms = keyboard.nextDouble();
            kilogramsConvertedToPounds = kilograms * WEIGHT_CONVERSION_FACTOR;
            System.out.println("The number of pounds in " + pounds +
            "pounds is " + kilogramsConvertedToPounds + ".");
            keyboard.nextLine();
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;

        } else{ 
            return;
        }
    }
}

7 个答案:

答案 0 :(得分:5)

在你从米到脚的情况下,你错过了一个正确的大括号。

在整个代码中还有一些其他的花括号问题 - 例如,在第47行,有一个你不想要的右支撑。检查您的块结构,并且在每种情况下,确保您在合理的情况下打开和关闭块。

答案 1 :(得分:5)

在将逻辑从一个地方复制到另一个地方时,通过不更改代码而犯了很多错误。通过减少重复可以大大改善你的代码,我会在'if''else'条件下更乐观地捕获正确的案例并将所有错误的案例留到最后......以下是工作版本通过修复拼写错误和逻辑顺序来略微修改代码。

import java.util.Scanner;

public class UnitConversion3b {
    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        String maxInputWarning = "\nError: Too many input characters."
                + "\nProgram is now terminating.";
        String lengthOrWeight;
        final double LENGTH_CONVERSION_FACTOR = 3.2808399;
        final double WEIGHT_CONVERSION_FACTOR = 2.20462;
        String whichWeightConversion = "empty", whichLengthConversion = "empty";
        double feet = 0, meters = 0, pounds = 0, kilograms = 0;
        double metersConvertedToFeet, feetConvertedToMeters;
        double poundsConvertedToKilograms, kilogramsConvertedToPounds;

        System.out.println("");
        System.out.print("What kind of value would you like to convert?");
        System.out.print("\nEnter L for length, or W for weight: ");

        lengthOrWeight = keyboard.nextLine();
        if (lengthOrWeight.length() > 1) {
            System.out.println(maxInputWarning);
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        } else if ((!(lengthOrWeight.equalsIgnoreCase("l")) && (!(lengthOrWeight
                .equalsIgnoreCase("w"))))) {
            System.out.println("\nError: Unrecognized conversion type."
                    + "\nProgram is now terminating.");
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
        } else if (lengthOrWeight.equalsIgnoreCase("l")) {
            System.out.println("\nConverting feet or meters?");
            System.out.print("Enter F to convert feet, or M for meters: ");
            whichLengthConversion = keyboard.nextLine();

            if (whichLengthConversion.length() > 1) {
                System.out.println(maxInputWarning);
                System.out.print("Press Enter to continue ... ");
                keyboard.nextLine();
                return;
            } else if ((!(whichLengthConversion.equalsIgnoreCase("f")) && (!(whichLengthConversion
                    .equalsIgnoreCase("m"))))) {
                System.out.println("\nError: Unrecognized unit of "
                        + "measurement.\nProgram is now terminating.");
                System.out.print("Press Enter to continue ... ");
                keyboard.nextLine();
                return;
            } else if (whichLengthConversion.equalsIgnoreCase("f")) {
                System.out.print("Enter the number of feet to"
                        + " convert to meters: ");
                feet = keyboard.nextDouble();
                feetConvertedToMeters = feet / LENGTH_CONVERSION_FACTOR;
                System.out.println(feet + " Feet in Meters is "
                        + feetConvertedToMeters + ".");
                keyboard.nextLine();
                System.out.print("Press Enter to continue ... ");
                keyboard.nextLine();
                return;
            } else if (whichLengthConversion.equalsIgnoreCase("m")) {
                System.out.print("Enter the number of meters to"
                        + " convert to feet: ");
                meters = keyboard.nextDouble();
                metersConvertedToFeet = meters * LENGTH_CONVERSION_FACTOR;
                System.out.println(meters + " Meters in Feet is "
                        + metersConvertedToFeet + ".");
                keyboard.nextLine();
                System.out.print("Press Enter to continue ... ");
                keyboard.nextLine();
                return;
            }
        }

        else {
            System.out.println("Converting pounds or kilograms?");
            System.out.print("Enter P to convert pounds, or K for kilograms: ");
            whichWeightConversion = keyboard.nextLine();

            if (whichWeightConversion.length() > 1) {
                System.out.println(maxInputWarning);
                System.out.print("Press Enter to continue ... ");
                keyboard.nextLine();
                return;
            } else if ((!(whichWeightConversion.equalsIgnoreCase("p")) && (!(whichWeightConversion
                    .equalsIgnoreCase("k"))))) {
                System.out.println("\nError: Unrecognized unit of "
                        + "measurement.\nProgram is now terminating.");
                System.out.print("Press Enter to continue ... ");
                return;
            } else if (whichWeightConversion.equalsIgnoreCase("p")) {
                System.out.println("Enter the number of pounds to"
                        + " convert to kilograms:");
                pounds = keyboard.nextDouble();
                poundsConvertedToKilograms = pounds / WEIGHT_CONVERSION_FACTOR;
                System.out.println(pounds + " Pounds in Kilograms is "
                        + poundsConvertedToKilograms + ".");
                keyboard.nextLine();
                System.out.print("Press Enter to continue ... ");
                keyboard.nextLine();
                return;
            } else if (whichWeightConversion.equalsIgnoreCase("k")) {
                System.out.print("Enter the number of kilograms to"
                        + " convert to pounds: ");
                kilograms = keyboard.nextDouble();
                kilogramsConvertedToPounds = kilograms
                        * WEIGHT_CONVERSION_FACTOR;
                System.out.println(kilograms + " Kilograms in Pounds is "
                        + kilogramsConvertedToPounds + ".");
                keyboard.nextLine();
                System.out.print("Press Enter to continue ... ");
                keyboard.nextLine();
                return;

            }
        }
    }
}

答案 2 :(得分:2)

我的教授让我们从正在开展工作的班级中分离出我们的主要班级。它有很大帮助。我知道这似乎是一项额外的工作,但是如果你将你的SOP /输入拉到一个DemoMain类中,然后将你的UnitConversion3b类分开,那么它将更容易阅读。另外,我知道很多人在关闭一个人之后就把他们放在了正确的位置,但老实说,如果我放下我的开头,我会发现自己的代码更容易阅读。我认为你的逻辑是明智的,但是很难说出支撑问题。我认为你有一些悬而未决的问题,你的意思是在条件中有一些陈述但实际上是在外面: - /

答案 3 :(得分:1)

尝试摆脱

(!(lengthOrWeight.equalsIgnoreCase("l"))
            && (!(lengthOrWeight.equalsIgnoreCase("w"))))){

并将以下块放在else

else{
    System.out.println("\nError: Unrecognized conversion type."
            + "\nProgram is now terminating.");
            System.out.print("Press Enter to continue ... ");
            keyboard.nextLine();
            return;
}

它可能没有帮助,但它会使事情更清楚。

另外,当你可以执行line.equalsIgnoreCase(“l”)时,你不需要检查长度,如果输入更长则它不会相等。

答案 4 :(得分:1)

它为您提供该错误的原因是因为Scanner的{​​{1}}方法返回行以及结束该行的换行符(nextLine())。

请尝试使用'\n'的{​​{1}}方法来截断任意一行的所有空格:

String

答案 5 :(得分:0)

我知道这可能听起来有点疯狂,但它确实有效:想象一下你的用户输入作为一个小动物你已经为它设置了一个陷阱。你需要捕捉动物并做一些事情。为了我们的动物爱好者的缘故,让我们说你需要抓住它,安静它,称重它,并在它上面放一个无线电项圈,然后相对不受伤害地释放它,只要它是Cougar类型。所以,我们的陷阱是一个多功能陷阱。无论输入什么,都会产生一个价值。

WHAM !!!陷阱里有东西。幸运的是,我们的陷阱是自动的。如果它没有落入浮动值,则陷阱打开并离开。它不是美洲狮。

好的,陷阱仍然关闭。它一定是美洲狮。我们可以继续努力。

现在,我们要求那个穿着香蕉共和国装备的人和他身边的大尼康一起寻求帮助。我们在陷阱中有这个Float值。现在,我们向Banana Repubic的科学家询问我们的数字意味着什么。

“嘿,科学家盖伊,我们陷阱中的数字是什么意思?”

如果“这是长度”,他回答:

This is the length of the Cougar in feet, I need it it converted to meters...

This is the length of the Cougar in  meters, I need it it converted to feet...

如果“这是重量”,他回答:

This is the weight in pounds, I need it converted to kilos...

This is the weight in kilos, I need it converted to pounds...

您可能会发现,当您考虑它时,您的老师会问'您如何设置问题'?换句话说,通过首先询问用户的值,您可以减少程序必须回答的问题数量。

答案 6 :(得分:0)

好的,所以这里有两个类的例子,一个主要的演示类和实际的工作类:

TestMain.java是这样的:

import java.util.Scanner;

public class TestMain
{
public static void main(String[] args) 
    {
    float theValue;
    float theAnswerIs;
    char getLengthOrWeight;
    String theValueAsString;
    boolean lOrW; //length or width
    boolean fOrM; //feet or meters
    boolean pOrK;  //pounds or kilos... it's a CS joke haha
    char getFeetOrMeters;
    char getPoundsOrKilos;


    //Set up a Scanner instance called keyboard   
    Scanner keyboard = new Scanner(System.in);

    UnitConversion3b converterInstance = new UnitConversion3b();

    //Request user for the number to convert
    System.out.println("What is the value you will be converting?");
    theValueAsString = keyboard.nextLine();

    //convert that value and trap
    theValue = floatToString(theValueAsString);


    //Request user for length or weight conversion
    System.out.println("What kind of value would you like to convert?"); 
    System.out.println("Enter L for length, or W for weight: ");
    //variable = console.next().charAt(0);
    getLengthOrWeight = keyboard.next().charAt(0);
    lOrW = converterInstance.lengthOrWeight(getLengthOrWeight);

    //create a new UnitConversion3B object and pass it the L or W or bad string the user inputs



    //if(true) then user asked for length
    if(lOrW)
    {
        System.out.println("\nConverting feet or meters?"); 
        System.out.print("Enter F to convert feet to meters, or M for meters to feet: ");
        //set our main's feetOrMeters variable to the value received when we ask our
        //converterInstance the question whichLengthConversion?
        getFeetOrMeters = keyboard.next().charAt(0);
        fOrM = converterInstance.feetOrMeters(getFeetOrMeters);

        //if(fOrM) aka user asked for a length conversion in feet, let's convert it:
        if(fOrM)
        {
            theAnswerIs = (float) (theValue * 3.28083);
            System.out.println("The answer is: " + theAnswerIs + " feet."); 
        }

        //if(!fOrM) aka user asked for a length conversion in meters, let's convert it:
        if(!fOrM)
        {
            theAnswerIs = (float) (theValue * 0.3048);
            System.out.println("The answer is: " + theAnswerIs + " feet."); 
        }
        //bad input should be trapped in the feetOrMeters function of the converterInstance
    }

    //if(false) then user asked for weight
    else if(!lOrW)
    {
      System.out.println("Converting pounds or kilograms?"); 
      System.out.print("Enter P to convert pounds to kilos, or K for kilograms to pounds: "); 

        getPoundsOrKilos = keyboard.next().charAt(0);
        pOrK = converterInstance.poundsOrKilos(getPoundsOrKilos);

        //if(pOrK) aka user asked for a pounds to kilos conversion, let's convert it:
        if(pOrK)
        {
            theAnswerIs = (float) (theValue * 0.45359237);
            System.out.println("The answer is: " + theAnswerIs + " feet."); 
        }

        //if(!pOrK) aka user asked for a kilos to pounds conversion, let's convert it:
        if(!pOrK)
        {
            theAnswerIs = (float) (theValue * 2.20462262);
            System.out.println("The answer is: " + theAnswerIs + " feet."); 
        }
        //bad input should be trapped in the poundsOrKilos function of the converterInstance

    }

}

private static float floatToString(String theValueAsString) {
    // thanks for this method from http://devdaily.com/java/edu/qanda/pjqa00013.shtml
    float f = 0;

    try
    {
      f = Float.valueOf(theValueAsString.trim()).floatValue();
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }


    return f;
}

}

和UnitConversion3b.java如下:

public class UnitConversion3b 
{

    private boolean lengthOrWeightSwitch;
    boolean feetOrMeters;
    final double LENGTH_CONVERSION_FACTOR = 3.2808399; 
    final double WEIGHT_CONVERSION_FACTOR = 2.20462;
    boolean poundsOrKilograms;

    public UnitConversion3b(String getLengthOrWeight) {
        if(getLengthOrWeight == "W")
            lengthOrWeightSwitch = true;
        else if(getLengthOrWeight == "L")
            lengthOrWeightSwitch = false;
        else
        {
            badInput();
        }   
    }

    public boolean getConversionType()
    {
        return lengthOrWeightSwitch;
    }

    public boolean whichLengthConversion(String whichLength)
    {

        if(whichLength == "F")
            feetOrMeters = true;
        else if(whichLength == "M")
            feetOrMeters = false;
        else
        {
            badInput();
        }
        return feetOrMeters;
    }

    public  boolean whichWeightConversion(String whichWeight)
    {

        if(whichWeight == "P")
            poundsOrKilograms = true;
        else if(whichWeight == "K")
            poundsOrKilograms = false;
        else
        {
            badInput();
        }
        return poundsOrKilograms;

    }


    public void badInput()
    {
        System.out.println("Invalid input");
        System.exit(0);
    }

    public String valueToFeet(float theValue) {
        //assumes value entered need to be converted from meters to feet
        return "" + (theValue*LENGTH_CONVERSION_FACTOR);
    }

    public String valueToMeters(float theValue) {
        //assumes value entered need to be converted from feet to meters
        return "" + (theValue/LENGTH_CONVERSION_FACTOR);
    }

    public String valueToPounds(float theValue) {
        // assumes value entered needs to be converted to pounds
        return ""+ (theValue * WEIGHT_CONVERSION_FACTOR);
    }

    public String valueToKilos(float theValue) {
        // TODO Auto-generated method stub
        return ""+ (theValue / WEIGHT_CONVERSION_FACTOR);
    }

    public void setConversionType(char getLengthOrWeight) {
        if(getLengthOrWeight == 'L')
            lengthOrWeightSwitch = true;
        if(getLengthOrWeight == 'W')
            lengthOrWeightSwitch = false;
        else
            badInput();
    }

    public boolean lengthOrWeight(char getLengthOrWeight) {
        if(getLengthOrWeight == 'L')
            return true;
        if(getLengthOrWeight == 'W')
            return false;

        return false;
    }

    public boolean feetOrMeters(char getFeetOrMeters) {
        if(getFeetOrMeters == 'F')
            return true;
        if(getFeetOrMeters == 'M')
            return false;

        //these functions return false under 'false' conditions... work on the logic :-) 
        return false;
    }

    public boolean poundsOrKilos(char getPoundsOrKilos) {
        if(getPoundsOrKilos == 'P')
            return true;
        if(getPoundsOrKilos == 'K')
            return false;

        //these functions return false under 'false' conditions... work on the logic :-) 
        return false;
    }


}

现在请注意,即使我正确地粘贴了这个,如果你输入这个代码,你的作业会得到一个比糟糕得分更差的作品。它编译并运行,但它忽略了你似乎限制在你的任务上的max char#输入。可能还有其他问题,不管怎样,我认为它是有些可跟随的代码。我可能想要进一步打破更多课程,但我希望这会有所帮助。