I have this programming assignment that converts between meters and feet, and between kilograms and pounds. When I tell the program I want to convert weight (by entering "w" when prompted), it gives me my the following error:
Error: Too many input characters error.
I worked on this for a long time, but can't figure it out. Can someone please tell me how to make the weight conversion work like the length conversion?
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;
}
}
}
You made lots of errors by not changing the code while copy pasting the logic from one place to the other. Your code can be improved a lot by reducing the repetitions and I will be more optimistic in my 'if' 'else' conditions to capture the right cases first and leaving all the wrong cases to the end...Below is the working version of your code modified slightly by fixing the typos and order of the logic.
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;
}
}
}
}
You're missing a right curly-brace after your meters-to-feet case.
There are some other curly-brace issues throughout your code -- for example, on line 47, there's a right brace where you don't want one. Check over your block structure and, in each case, make sure you're opening and closing blocks where it makes logical sense to do so.
My professor makes us seperate our main class from the Class that is doing the work. It helps a lot. I know it seems like a lot of extra work, but if you pulled your SOPs/inputs out into a DemoMain class and then had your UnitConversion3b class seperate it would be a lot easier to read. Also, I know a lot of people put their {'s right after the close of a paren, but honestly I find my own code a lot easier to read if I drop my opening { down a line. I think your logic is good statement wise, but it's so hard to tell with the brace issues. I think you have some hanging if issues, where you mean to have some of the statements inside a conditional but they are actually outside :-/
Try getting rid of
(!(lengthOrWeight.equalsIgnoreCase("l"))
&& (!(lengthOrWeight.equalsIgnoreCase("w"))))){
and just putting the following block in the else
else{
System.out.println("\nError: Unrecognized conversion type."
+ "\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
}
It might not help but it will make things clearer.
Also you don't need to check length when you can do line.equalsIgnoreCase("l"), if the input is longer it will not be equal.
The reason why it gives you that error is because Scanner's nextLine() method returns the line as well as the newline character ('\n') that ends the line.
Try this line instead, using String's trim() method to cut off all whitespace from either end :
lengthOrWeight = keyboard.nextLine().trim();
OK, so here is an example of two classes, a main demo class and the actual working class:
TestMain.java goes like this:
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;
}
}
and UnitConversion3b.java goes like:
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;
}
}
Now please note, even if I pasted this correctly you are going to get a worse than bad score on your assignment if you turn in this code. It compiles and runs, but it ignores the max char# input you seemed to have constrained on your assignment. Probably there are other issues, howver, I think it is somewhat followable code. I would probably want to break it even further into more classes, but I hope this helps.
I know this may sound a little nutty, but it works: Imagine your user input as a little animal and you have set a trap for it. You need to catch the animal and do something to it. For our animal lovers' sake, let's say you need to catch it, tranquilize it, weigh it, and put a radio collar on it and then release it relatively unharmed provided it is of type Cougar. So, our trap is a multi-function trap. Whatever enters it, a value will be produced.
WHAM!!! Something is in the trap. Luckily, our trap is automatic. If it doesn't land a float value, then the trap opens and it leaves. It isn't a Cougar.
OK, the trap is still closed. It must be a Cougar. We can work on it.
Now, we ask the guy wearing the Banana Republic gear with the big Nikon around his neck for some help. We have this Float value in the trap. Now, we ask the Scientist in the Banana Repubic gear what our number means.
"Hey, Scientist Guy, what does the number in our trap mean?"
If "It's the length", he answers:
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...
If "it's the weight", he answers:
This is the weight in pounds, I need it converted to kilos...
This is the weight in kilos, I need it converted to pounds...
You may find that, when you think about it, your Teacher was asking 'how do you set up the problem'? In other words, by asking the user for the value first, you can cut down on the amount of questions the program has to answer.
Related
I'm writing a program in Java that does temperature conversion, but running into an issue.
import java.util.*;
public class TempCon2 {
public static void main (String[] args) {
double f,c,temp;
char ch,op;
Scanner sc = new Scanner(System.in);
System.out.println("This program converts temperatures from Fahrenheit to Celsius and vica versa.");
do {
System.out.print("Please enter your temperature: ");
temp = sc.nextDouble();
System.out.print("Please enter the units (F/C): ");
ch = sc.next().charAt(0);
if(ch=='F') {
c=(temp-32)*5/9;
System.out.println("\nThe temperature of " + temp + " degrees Fahrenheit is equivalent to " + c + " degrees Celsius!"); }
else if(ch=='C') {
f=(temp*9/5)+32;
System.out.println("\n The temperature of " + temp + " degrees Celsius is equivalent to " + f + " degrees Fahrenheit!"); }
System.out.print("Do you wish to do another conversion? (Y/N): ");
op=sc.next().charAt(0);
System.out.println();
if(op=='N' || op=='n') {
break; }
}while((op=='Y' || op=='y'));
System.out.println("Thank you, Goodbye");
}
}
I want to be able to check when the user inputs their temperature if its a number, and if not it returns a message that says " 'user input' is not a number. Please enter a number". As well as when it asks for the units that if you enter anything other than "F" or "C" it does the same as the number one.
You can try by parsing the String value to Double:
Double temp;
try {
temp = Double.parseDouble(sc.nextLine());
} catch (NumberFormatException nfe){
System.out.println("The input is not a number");
break;
}
From Double.parseDouble doc:
NumberFormatException – if the string does not contain a parsable
double.
What you want is 'complex', in the sense that you don't hunt for a single method that does this; there is no scanner.askForCorFAndKeepAskingIfTheyEnterSomethingElse();.
So, you do the same thing you always do when faced with a task you want to do repeatedly which isn't trivial: You make a method.
public static char askTemperatureUnit(Scanner s) {
...
}
public static double askTemperatureAmount(Scanner s) {
...
}
These methods will use a few aspects:
a while (true) loop. If the result is what you wanted, return it. (which also ends the loop by returning out of it). Otherwise, you tell the user they didn't enter what you wanted and let it loop.
A way to respond when the user fails to enter a double value:
while (true) {
try {
return scanner.nextDouble();
} catch (InputMismatchException e) {
scanner.next(); // eat the invalid input away
System.out.println("Hey now enter a number please!");
}
}
You can also call scanner.next() and then use try/catch to run Double.parseDouble - same end result, whatever you feel is best.
While you're at it, c = Character.toUpperCase(c) lets you turn an n into an N which is nice.
You need a couple of more do-while loops the way you have put for prompting the user if they want to continue.
I also recommend you use Scanner::nextLine to avoid the problems mentioned in this thread.
public class Main {
public static void main(String[] args) {
double f, c, temp;
char ch, op;
Scanner sc = new Scanner(System.in);
System.out.println("This program converts temperatures from Fahrenheit to Celsius and vica versa.");
do {
boolean valid;
do {
valid = true;
System.out.print("Please enter your temperature: ");
try {
temp = Double.parseDouble(sc.nextLine());
do {
valid = true;
System.out.print("Please enter the units (F/C): ");
ch = sc.nextLine().charAt(0);
if (ch == 'F') {
c = (temp - 32) * 5 / 9;
System.out.println(
"\nThe temperature of " + temp + " degrees Fahrenheit is equivalent to " + c
+ " degrees Celsius!");
} else if (ch == 'C') {
f = (temp * 9 / 5) + 32;
System.out
.println("\n The temperature of " + temp + " degrees Celsius is equivalent to " + f
+ " degrees Fahrenheit!");
} else {
System.out.println("Invalid input. Enter F or C");
valid = false;
}
} while (!valid);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Enter a number only");
valid = false;
}
} while (!valid);
System.out.print("Do you wish to do another conversion? (Y/N): ");
op = sc.nextLine().charAt(0);
System.out.println();
if (op == 'N' || op == 'n') {
break;
}
} while ((op == 'Y' || op == 'y'));
System.out.println("Thank you, Goodbye");
}
}
A sample run:
This program converts temperatures from Fahrenheit to Celsius and vica versa.
Please enter your temperature: abc
Invalid input. Enter a number only
Please enter your temperature: 12.5
Please enter the units (F/C): X
Invalid input. Enter F or C
Please enter the units (F/C): F
The temperature of 12.5 degrees Fahrenheit is equivalent to -10.833333333333334 degrees Celsius!
Do you wish to do another conversion? (Y/N): y
Please enter your temperature: xyz
Invalid input. Enter a number only
Please enter your temperature: pqr
Invalid input. Enter a number only
Please enter your temperature: -40
Please enter the units (F/C): a
Invalid input. Enter F or C
Please enter the units (F/C): F
The temperature of -40.0 degrees Fahrenheit is equivalent to -40.0 degrees Celsius!
Do you wish to do another conversion? (Y/N): n
Thank you, Goodbye
My code is about looping and method, A program that will let user either compute an area or use the 4 basic math operations. the (Triangle, Square,Rectangle) with their choice of process: Addition, Subtraction, Multiplication and Division.
I think i properly closed the addition function there and i already check the closing every functions they seem work well other than the addtion function since thats the only error i got.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//WHILE LOOP FOR CHOICES
while(true){//CHOICES LOOP
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("1 - Addition process");
System.out.println("2 - Subtraction process");
System.out.println("3 - Multiplication process");
System.out.println("4 - Division process");
System.out.println("5 - Compute process");
System.out.println("Your choice: ");
int option = scan.nextInt();
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if(option == 1){
Add();
}
else if(option == 2){
Sub();
}
else if(option == 3){
Mul();
}
else if(option == 4){
Div();
}
else if(option == 5){
Com();
}
else if((option>=6)&&(option<=100)){//INVALID
System.out.println("Invalid Input, Please Input Choice Again.");
}
else{//- if user input other number, the program will break and stop from looping
break;
}
Here Im getting a error here im not sure what is it
public static void Add(){
System.out.println("ADDITION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int add1=scan.nextInt();
System.out.println("2nd number: ");
int add2=scan.nextInt();
int addtotal=add1+add2;
if(addtotal>100){// In addition, if the sum is higher than 100, print the answer the word high. if equal and below 100, print low
System.out.println("Total is "+addtotal+" High");
}
else if(addtotal<100){
System.out.println("Total is "+addtotal+" Low");
}
}
public static void Sub(){//SUBTRACTION
System.out.println("SUBTRACTION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int sub1=scan.nextInt();
System.out.println("2nd number: ");
int sub2=scan.nextInt();
int subtotal=sub1-sub2;
if(subtotal<0){// In subtraction, if the difference is negative, print invalid. If 0 or above, print the difference and the word valid.
System.out.println("Invalid ");
}
else if(subtotal>0){
System.out.println("Total is "+subtotal+" Valid");
}
}
public static void Mul(){//MULTIPLICATION
System.out.println("MULTIPLICATION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
double multi1=scan.nextDouble();//In multiplication, make it accepts decimal value
System.out.println("2nd number: ");
double multi2=scan.nextDouble();
double multitotal=multi1*multi2;
System.out.println("Total is "+multitotal);
}
public static void Div(){
System.out.println("DIVISION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int div1=scan.nextInt();
System.out.println("2nd number: ");
int div2=scan.nextInt();
int divtotal= div1 / div2;
int divremainder= div1 % div2;//In division, if it has remainder, print the answer and the remainder.
System.out.println("Total is "+divtotal);
System.out.println("Remainder is "+divremainder);
}
public static void Com(){// If user choose 5, the user needs to choose again on a ,b or c. If other letter, print invalid and then go pack on choosing of process.
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("a - Rectangle");
System.out.println("b - Square");
System.out.println("c - Triangle");
System.out.println("Your choice: ");
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
char choice = Keyboard.nextLine().charAt(0);
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if (choice == 'A' || choice == 'a')//rectangle
{
System.out.println("Enter length of rectangle's base: ");
double base = input.nextDouble();
System.out.println("Enter length of rectangle's height: ");
double height = input.nextDouble();
double rArea = base * height;
System.out.println("The area of a rectangle with a base length of " + base + " and a height of " + height + " is " + rArea + ".");
}
else if (choice == 'B' || choice == 'b') //square
{
System.out.println("Enter length of square's sides: ");
double sSide = input.nextDouble();
double sArea = sSide * sSide;
System.out.println("The area of a square with a side length of " + sSide + " is " + sArea + ".");
}
else if (choice == 'C' || choice == 'c') //traingle
{
System.out.println("Enter traingle's side length: ");
double tSide = input.nextDouble();
double tArea = tSide * tSide * tSide;
System.out.println("The area of a triangle with a side length of " + tSide + " is " + tArea + ".");
}
else //invalid
{
System.out.println("You've entered an invalid character.");
}
}
}
You haven't got a closing brace for your main method
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean start = true;
while(start)
System.out.printf("%70s %n", " ##### Zoos Australia ##### " + "\n");
System.out.printf("%57s %n", "Main Menu" + "\n");
System.out.printf("%72s %n", "Zoo has the following ticketing options:");
System.out.print("\n");
System.out.printf("%59s %n", "1 = Child (4-5 yrs)");
System.out.printf("%59s %n", "2 = Adult (18+ yrs)");
System.out.printf("%60s %n", "3 = Senior (60+ yrs)");
System.out.println("\n");
String choose1 = "";
String choose2 = "";
String choose3 = "";
String selected = "";
int option = 0;
{
System.out.print("Please select an option: ");
option = input.nextInt();
if (option == 1) {
choose1 = "Child";
selected = choose1;
} else if (option == 2) {
choose2 = "Adult";
selected = choose2;
} else if (option == 3) {
choose3 = "Senior";
selected = choose3;
}
}
// done
System.out.println("\n");
int price = 0;
int tickets = 0;
System.out.print("Enter the number of tickets: ");
tickets = input.nextInt();
if (selected == choose1) {
price = 10;
} else if (selected == choose2) {
price = 20;
} else if (selected == choose3) {
price = 15;
}
System.out.println("\n");
System.out.print("You are purchasing " + tickets + " " + selected + " tickets at " + "$" + price + " each!");
System.out.println("\n");
int confirm = 0;
System.out.print("Press 1 to confirm purchase: ");
confirm = input.nextInt();
if (confirm != 1) {
System.out.print("Incorrect Key. Please return to Main Menu");
System.out.println("\n");
} else {
break;
}
System.out.println("\n");
int total = tickets;
price = total * price;
System.out.print("Total amount for " + selected + " tickets: " + "$" + price);
System.out.println("\n");
String pick = "";
System.out.print("Do you wish to continue: ");
input.next();
System.out.println("\n");
if (pick == "no") {
System.out.print("Total amount payable is: " + "$" + price);
System.out.println("\n");
System.out.print("Have a nice day!");
System.out.println("\n");
}}}
Trying to do this at the end of the program where user is asked "Do you wish to continue" using a method or something but cant get it to work. Either the program returns to main menu only or the program ends and displays the total message "Total amount payable..." etc. I have tried using while with continue and break. Using boolean with true and false. But no luck. Thank you anyone that may be able to clear this up for me please.
First, you have to assign the users's input to a variable: pick = input.next(). After that, the problem is that you compare the user's input string with a "no" string by using == operator. When comparing reference types (objects) (and String is an object), in most cases == operator gives you an unpredictable result, because it compares the reference (address of an object in memory) and not the actual content. Please remember, that you always have to use the .equals() method instead. You also have to break from your loop, when the user's input is "no".
There is plenty of material concerning this issue. You can check, for instance, this one How do I compare strings in Java?
P.S. I quickly looked at the rest of your code and put some additional comments, which might help you to improve it. Good luck with learning Java!
Scanner input = new Scanner(System.in);
// boolean start = true; you don't need this line
while(true) { // 'true' condition makes it an infinite loop until you use break
// You also have to surround your while loop with curly braces,
// otherwise you fall into an infinite loop
System.out.printf("%70s %n", " ##### Zoos Australia ##### \n");
System.out.printf("%57s %n", "Main Menu\n");
System.out.printf("%72s %n", "Zoo has the following ticketing options: \n");
System.out.printf("%59s %n", "1 = Child (4-5 yrs)");
System.out.printf("%59s %n", "2 = Adult (18+ yrs)");
System.out.printf("%60s %n", "3 = Senior (60+ yrs)\n");
String choose1 = "";
String choose2 = "";
String choose3 = "";
String selected = "";
int option = 0;
System.out.print("Please select an option: ");
option = input.nextInt();
if (option == 1) {
choose1 = "Child";
selected = choose1;
} else if (option == 2) {
choose2 = "Adult";
selected = choose2;
} else if (option == 3) {
choose3 = "Senior";
selected = choose3;
}
System.out.println(); // "\n" is a redundant argument
int price = 0;
int tickets = 0;
System.out.print("Enter the number of tickets: ");
tickets = input.nextInt();
if (selected.equals(choose1)) { // you should never compare strings with == operator! Always use .equals() instead
price = 10;
} else if (selected.equals(choose2)) {
price = 20;
} else if (selected.equals(choose3)) {
price = 15;
}
System.out.println();
System.out.print("You are purchasing " + tickets + " " + selected + " tickets at " + "$" + price + " each!");
System.out.println();
int confirm = 0;
System.out.print("Press 1 to confirm purchase: ");
confirm = input.nextInt();
if (confirm != 1) {
System.out.print("Incorrect Key. Please return to Main Menu");
System.out.println("\n");
} else {
//break; you cannot use 'break' in the if statement! You have to figure out another way, how to handle an invalid input
}
System.out.println();
int total = tickets;
price = total * price;
System.out.print("Total amount for " + selected + " tickets: " + "$" + price);
System.out.println();
String pick = "";
System.out.print("Do you wish to continue: ");
pick = input.next(); // you have to assign the input to a variable
System.out.println();
if (pick.equals("no")) { // You have to ALWAYS use .equals() when comparing Strings or any other reference types! == works correctly only with primitive types
System.out.print("Total amount payable is: " + "$" + price);
System.out.println();
System.out.print("Have a nice day!");
System.out.println();
break; // you need to break from the loop in the end
}
}
}
recently started computer programming and I am stuck on a homework assignment. I created a loop but instead of going back to the top, it starts 1 step ahead of where I intended it to. (it's all listed in the comments I made in the coding. I have been trying to figure this out for the past 6 hours so it would greatly appreciated if someone can help me.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
DecimalFormat n = new DecimalFormat("##");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
response = scan.next();
while (response.equals("y"))
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
break;
//not returning to point A, instead it returns to point B
}
if (response.equals("n"))
{
break;
}
if (response.equals("n"))
{
break;
}
}
}
while (response.equals("n"));
System.out.println("Final Tally");
System.out.println("Polly received:\t " + n.format(totalPolly) + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + n.format(totalErnest) + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
My guess is that the string response has already been determine to be y at the end of the loop which is why it skips the first step and jumps right back into the loop assuming my answer is already y.
You will just need to strip your code of unnecessary breaks and also handle the 2 responses differently. Your loop should also continue when the response is y, not the other way round.
See edited code below:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
DecimalFormat n = new DecimalFormat("##");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
String response2 = scan.next();//create a new response variable, so the loop doesn't confuse which response to break on
//I removed the inner loop. If you really intended for this to be an inner loop then the while(response2.equals("y")){} should be around the question, not after
if (response2.equals("y"))
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
}
//removed the unnecessary checks for when response in 'n'
}
}
while (response.equals("y"));
System.out.println("Final Tally");
System.out.println("Polly received:\t " + n.format(totalPolly) + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + n.format(totalErnest) + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
if (response.equals("n"))
{
break;
}
breaks your while loop.
You might want to loop again if user's response if 'y'.
In that case, use while (response.equals("y"));
Your requirement is to break out if the user enters "n" but loop while the user input is "y", but your code says,
do{
.....
}while (response.equals("n"));
It should be,
while (response.equals("y"));
do {
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
#code
if (response.equals("n")) //<--- this 'if' block will break the loop when response equals 'n'
{
break;
}
}
}
while (response.equals("n"));// <----- this means doing loop when response equals "n"
You can see my comment on above block of code, the loop will do one more time only when response equals 'n'. But when response equals 'n', the 'if' block at above of it will break the loop and the while (response.equals("n")) will be not checked.
I have a program that asks the user their name etc. Then it asks how many times do you want the numbers to loop (so my program generates 3 random numbers between 7 and 13 and if it adds up to 31 they are the winner) and my issue is that I only want the last printed number to count towards if the player wins or looses, the other numbers are just for show or tease i guess. the problem is that regardless towards if the player wins or looses, the losing statement always prints out. Below is my entire code.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
//enter their first name
String first_name;
System.out.print("Enter Your First Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
//enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
//full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
//this is the buffer that resets if the user types a letter instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out
.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13" );
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
Arraylist numberStore = new Arraylist();
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// if pressed y or yes the program will run again with the same number of shuffles entered from before
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
you probably want something like
int lastNumber = numberStore.get(numberStore.size() - 1);
if (lastNumber == 31) {
to verify that is the error try to change that line to
int lastNumber = num1 + num2 + num3;
Edit based on further messages:
Looks like what you really want is this:
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = num1 + num2 + num3;
boolean lastShuffle = (i == (numShuffles - 1));
if (lastShuffle) {
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
} else {
System.out.println("Better Luck Next Time");
}
}
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
Just a general suggestion: avoid to use break if possible, it makes control flow hard to follow and is not a good programming practice.
Several points to make here. One, your code is quite messy and hard to read. It's helpful when you're asking for help (and in general anyway) to properly indent your code. This is good practice and if you do other languages like Python can help you out a lot. Also, why do a check for !isWinner? Scrap the isWinner variable altogether and just check for the number equalling 31 and then have an else statement for the losing statement. Like this:
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
else {
System.out.println("Better Luck Next Time");
}
Also, take some steps to find the error. Print out each number as you get it, and use
int lastNumber = num1 + num2 + num3;
instead of
int lastNumber = (numberStore.size() - 1);
Also for anybody else compiling this, it's ArrayList and not Arraylist... just a little slip.
Sorry, I may have to say that your codes are a kind of mess up. a small factory with the solution you ask, hope it can be a little help to you
public static void main(String[] args) throws NumberFormatException,
IOException {
Scanner user_input = new Scanner(System.in);
String full_name = registeGamePlayer(user_input);
int numShuffles = initGame(user_input);
showTheGameInfo(full_name, numShuffles);
runningGame(user_input, numShuffles);
user_input.close();
}
/**
* #param user_input
* #param numShuffles
*/
private static void runningGame(Scanner user_input, int numShuffles) {
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
int amount = num1 + num2 + num3;
System.out.printf("%d + %d + %d = %d \n", num1,num2,num3,amount);
if (amount == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
// if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
}
/**
* #param full_name
* #param numShuffles
*/
private static void showTheGameInfo(String full_name, int numShuffles) {
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
private static String registeGamePlayer(Scanner user_input){
String first_name;
System.out.print("Enter Your First Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
// enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
// full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
return full_name;
}
private static int initGame(Scanner user_input){
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
// this is the buffer that resets if the user types a letter
// instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
return numShuffles;
}