我无法弄清楚我的简单 Java 作业
Posted
技术标签:
【中文标题】我无法弄清楚我的简单 Java 作业【英文标题】:I can't figure out my simple Java homework 【发布时间】:2011-04-20 09:48:00 【问题描述】:我有一个在米和英尺之间以及公斤和磅之间转换的编程任务。当我告诉程序我想转换重量时(在提示时输入“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;
【问题讨论】:
请注意,如果您的代码格式更具可读性,调试会容易得多。放置空格确实很有帮助,您可以将w
或 l
校验重写为 if(!(lengthOrWeight.equalsIgnoreCase("l") || lengthOrWeight.equalsIgnoreCase("w")))
,这是一种更简洁(和清晰)的放置方式。
如果你想要更多积分,try to not repeat yourself.
谢谢。我觉得自己像个白痴错过了 ||代替 &&。我当然也让我的代码更具可读性。
【参考方案1】:
您在将逻辑从一处复制粘贴到另一处时没有更改代码,从而犯了很多错误。你的代码可以通过减少重复来改进很多,我会更乐观地在我的“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;
【讨论】:
johnbk,谢谢你的帮助。我现在正在比较你的代码和我的代码。 @user465001 - 好的..当您完成家庭作业时,请接受对您帮助最大的最佳答案..:)【参考方案2】:在米到英尺的情况下,您缺少右花括号。
在整个代码中还有一些其他的大括号问题——例如,在第 47 行,有一个您不想要的右大括号。检查你的块结构,在每种情况下,确保你在合乎逻辑的地方打开和关闭块。
【讨论】:
尝试使用 Java 代码格式化程序自动缩进您的代码;这比用肉眼追踪牙套要容易得多。如果您的 IDE 没有,请参阅 ***.com/questions/996646/… 正确的花括号到底应该放在哪里?抱歉,但我不熟悉查看代码,如您所见,我的格式也不好。这个缺少的花括号会使程序正常运行还是有很多花括号把它搞砸了? 就像我说的,这不是您遇到的唯一问题。请记住,花括号表示被视为逻辑单元的代码块——例如,if (this condition is true) do all of this stuff;
您需要我建议的花括号,因为如果 lengthOrWeight 为 "l"
,它将结束要执行的代码块。
感谢 Lee 和 Etaoin 帮助我!【参考方案3】:
我的教授让我们把我们的主要班级与正在做这项工作的班级分开。它有很大帮助。我知道这似乎需要做很多额外的工作,但是如果您将 SOP/输入拉到 DemoMain 类中,然后将 UnitConversion3b 类分开,那么阅读起来会容易得多。另外,我知道很多人把他们的 放在括号结束后,但老实说,如果我将开头的 放在一行中,我发现我自己的代码更容易阅读。我认为您的逻辑是明智的陈述,但是很难说大括号问题。我认为你有一些悬而未决的问题,你的意思是在条件内有一些语句,但它们实际上在外面:-/
【讨论】:
谢谢。当我开始工作时,我会花一些时间来做这件事。抱歉,眼睛太难受了。 实际上您应该尝试将您的应用程序分开,以便每个类都有一个由其名称指示的主要职责(这很困难但之后非常有用)。对你的函数做同样的事情 ...尽量避免使用很长的方法/同时尝试为您的类和方法提供良好的描述性名称,这可能很难(Phil Karton 说计算机中只有两个难题科学:缓存失效,命名事物)但是尝试一下,最好的 ide 功能之一是它可以帮助您以后重命名事物而不会破坏代码。【参考方案4】:试着摆脱
(!(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")时,你不需要检查长度,如果输入更长,它将不相等。
【讨论】:
【参考方案5】:它给你这个错误的原因是因为Scanner
的nextLine()
方法返回了行以及结束行的换行符('\n'
)。
试试这一行,使用 String
的 trim()
方法从两端截断所有空格:
lengthOrWeight = keyboard.nextLine().trim();
【讨论】:
【参考方案6】:好的,下面是两个类的示例,一个主要的演示类和实际的工作类:
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;
现在请注意,即使我正确粘贴了此代码,如果您上交此代码,您的作业也会得到比差评更差的分数。它编译并运行,但它忽略了您似乎限制在分配中的最大 char# 输入。可能还有其他问题,但是,我认为这是一些可遵循的代码。我可能想把它进一步分解成更多的类,但我希望这会有所帮助。
【讨论】:
【参考方案7】:我知道这可能听起来有点疯狂,但它确实有效:将您的用户输入想象成一只小动物,而您已经为它设置了一个陷阱。你需要抓住动物并对它做点什么。看在我们动物爱好者的份上,假设你需要抓住它,安抚它,称重,然后在它上面套上无线电项圈,然后如果它是美洲狮类型,则相对安然无恙地释放它。所以,我们的陷阱是一个多功能的陷阱。无论输入什么,都会产生一个值。
哇!!!陷阱里有东西。幸运的是,我们的陷阱是自动的。如果它没有达到浮点值,则陷阱打开并离开。这不是美洲狮。
好的,陷阱仍然关闭。应该是美洲狮。我们可以继续努力。
现在,我们请那个戴着香蕉***装备、脖子上挂着大尼康的家伙寻求帮助。我们在陷阱中有这个浮点值。现在,我们问香蕉***的科学家,我们的数字是什么意思。
“嘿,科学家家伙,我们陷阱里的数字是什么意思?”
如果“是长度”,他会回答:
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...
您可能会发现,当您考虑它时,您的老师会问“您如何设置问题”?换句话说,通过首先询问用户的值,您可以减少程序必须回答的问题数量。
【讨论】:
奎因,感谢您的建议和示例。他们帮助我从这项作业中了解更多信息。以上是关于我无法弄清楚我的简单 Java 作业的主要内容,如果未能解决你的问题,请参考以下文章
Pytorch 模型在 CPU 和 GPU 上都内存不足,无法弄清楚我做错了啥