my problem is that in my code, the if statement I have is supposed to take from a certain pot and then return the value but instead it takes values from both pots instead of one, can't figure out how to fix it. Also my other issue is that every time it takes candy from one pot its supposed to switch to that other pot, how can i do that? The if statement I'm talking about is in the class PassOutCandy.
import java.util.Random;
public class TreatHouse {
int candyPot1; // amount of candy in pot 1
int candyPot2; // amount of candy in pot 2
int currentPot; // 1 or 2
int totalCandy;
int currentTreaters; // variables
int treatsPerTreater;
public TreatHouse(int candyPot, int totalCandy) {
// Add code here, be sure to split the candy between the pots.
currentPot = candyPot;
this.totalCandy = totalCandy;
if (totalCandy <=0) {
System.out.println("We can't give out candy if we don't have amy. I think we have some from last year. " +
"Yep, we have 100 pieces of candy to give out.");
totalCandy = 100;
candyPot1 = totalCandy/2; // splits candy between both pots and sets totalCandy to 100 if user puts in false input
candyPot2 = totalCandy/2;
}
if (totalCandy > 0) {
this.totalCandy = totalCandy;
candyPot1 = totalCandy/2; // with correct user input splits the candy properly between both pots
candyPot2 = totalCandy - candyPot1;
}
}
public int getCandyCount() {
return candyPot1 + candyPot2; // total candy left
}
public void passOutCandy() {
//If there are enough treats per treater for the given amount per treater, pass out candy
//from the current pot and switch to the other one.
//Else display a message that the treaters have been tricked... (no candy for them.)
// but do not change the current pot
if ((totalCandy > 0) && (treatsPerTreater < totalCandy)) {
if (currentPot == 1 || currentPot == 2) {
if (currentPot == 1) {
candyPot1 = candyPot1 - (this.currentTreaters*this.treatsPerTreater);
}
if (currentPot == 2) {
candyPot2 = candyPot2 - (this.currentTreaters*this.treatsPerTreater);
}
}
else
System.out.println("Pot " + currentPot + " doesn't exist. Try again next time");
}
else
System.out.println("You have been tricked! No candy for you >:D!!!!");
}
//Sets the number of trick or treaters.
public void knockKnock() {
Random gen = new Random(System.currentTimeMillis());
this.currentTreaters = gen.nextInt(13) + 1; //1 to 13 treaters.
}
//Displays how much candy in each pot, total candy left
public void getCandyStatus() {
//add in code here
System.out.println("Candy in Pot1: " + candyPot1 + " Candy in Pot2: " + candyPot2); // will display candy in pot 1 / pot 2
System.out.println("Total candy left: " + (candyPot1 + candyPot2)); // total candy left
}
//returns the pot number for which candy was last given.
public int getLastPot() {
if (currentPot == 1 || currentPot == 2) {
if (currentPot == 2) { // returns the last pot that candy was taken from
currentPot = 1;
return currentPot;
}
if (currentPot == 1) {
currentPot = 2;
return currentPot;
}
}
else
return currentPot;
}
public void setTreatsPerTreater(int treatsPerTreater) {
//add code here
this.treatsPerTreater = treatsPerTreater; // sets the proper amount of treats per treater from user input
}
}
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
What's the simplest way to print a Java array?
(37 answers)
Closed 10 months ago.
I have a method called processClaims() which takes input from the user "by asking how many files need to be claimed". The method is shown below.
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
The problem is with the array or the for loop I belive. The output is shown below which isn't correct
[LInsuranceSystem$EarthquakeInsurance;#548c4f57
If that is wrong here is the whole code, I am having trouble debugging this.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
public class Slack
{
public static void main(String[] args) throws FileNotFoundException {
InsuranceSystem insuranceSystem = new InsuranceSystem();
insuranceSystem.start();
}
}
class InsuranceSystem {
Scanner input = new Scanner(System.in);
Calendar dateTime = Calendar.getInstance();
ArrayList<String> claimsReport = new ArrayList<>();
EarthquakeInsurance[] claims;
String fileName = " ";
char cont = ' ', correct = ' ';
public InsuranceSystem() {
}
public void start() throws FileNotFoundException {
System.out.println("MUTUALLY ACCIDENTAL INC.");
System.out.println("Do you want an analysis of earthquake coverage for your property? Enter 'Y' or 'N': ");
cont = input.next().charAt(0); //reads user input from input and applies to it var cont
input.nextLine(); //clears buffer
if (cont == 'y' || cont == 'Y') {
processClaims();
writeClaimsRecords();
checkInputFile();
}
printThankYou();
}
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
public void writeClaimsRecords() throws FileNotFoundException
{
String record = " ";
Scanner input = new Scanner(System.in);
System.out.println("Enter the file name for the claims' records (WARNING: This will erase a pre-existing file!): ");
fileName = input.nextLine();
PrintWriter outputFile = new PrintWriter(fileName);
for(int i = 0; i < claims.length; i++){
record = String.format("%s, %f, %f%n", claims[i].insured, claims[i].homeInsVal, claims[i].richter);
}
outputFile.printf(record);
outputFile.close();
System.out.println("Data written to the" + fileName + " file.");
}
public void checkInputFile() throws FileNotFoundException {
String fileRecord = " ";
File file = new File("Claims.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()) {
fileRecord = inputFile.nextLine();
System.out.println(fileRecord);
System.out.println("");
inputFile.close();
}
}
public void printThankYou() {
System.out.println("Thank you for using the Earthquake Coverage Analyzer.");
}
class EarthquakeInsurance {
//STUDENTS INSERT LINE COMMENTS DESCRIPTIVE OF THE PURPOSE OF EACH VARIABLE.
private String insured;
private String coverage;
private String message;
private double homeInsVal;
private double richter;
private double payout;
private double deductible;
private Scanner input = new Scanner(System.in);
private boolean repeat;
private char correct;
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance() {
}//END Default Constructor
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance(String insured, double homeInsVal, double richter) {
setInsured(insured);
setHomeInsVal(homeInsVal);
setRichter(richter);
}//END EarthquakeInsurance(String, double, double)
/**
* STUDENTS CODE copy() AND PROVIDE METHOD BOX COMMENTS.
*/
public String copy() {
String insuranceObj = " ";
return insuranceObj;
}
/**
* STUDENTS CODE equals AND PROVIDE METHOD BOX COMMENTS.
*/
public boolean equals(String aClaim) {
boolean isEqual = false;
if (isEqual = false) {
isEqual = true;
}
return isEqual;
}
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setInsured(String insured) {
this.insured = insured;
}//END setInsured(String): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setHomeInsVal(double homeInsVal) {
this.homeInsVal = homeInsVal;
}//END setHomeInsVal(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setRichter(double richter) {
this.richter = richter;
}//END setRichter(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setInsured() {
String insuredCopy = null, first = null, last = null;
int indexOfSpace = 0;
do {
System.out.printf("%nMUTUALLY ACCIDENTAL, INC."
+ "%nEarthquake Coverage Analyzer"
+ "%n%nPlease enter your name: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
while (!isAlpha(insuredCopy)) {
System.out.printf("%nInvalid name! Please re-enter: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
}//while insured's name is NOT alphabetic
System.out.printf("%nYour Name: %s"
+ "%n%nIs this name correct? \'Y\' or \'N\': ",
insured);
correct = input.nextLine().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
} while (repeat); //do-while insured name is not correct
indexOfSpace = insured.indexOf(" "); //Locate where the space is in insured.
if (indexOfSpace > 0) {
first = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, indexOfSpace).toLowerCase();
last = Character.toUpperCase(insured.charAt(indexOfSpace + 1))
+ insured.substring(indexOfSpace + 2, insured.length()).toLowerCase();
insured = first + " " + last;
}//if there is more than one name, capitalize the first letter in each
else {
insured = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, insured.length()).toLowerCase();
}//else capitalize first letter of a single name
}//END setInsured(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setHomeInsVal() {
do {
do {
System.out.printf("%nPlease enter the insured value of your home: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when homeInsVal is invalid
homeInsVal = input.nextDouble();
if (homeInsVal < 0) {
System.out.printf("%nThe insured value of your home cannot be less than or equal to 0.%n");
repeat = true;
}//END if homeInsVal less than zero then prompt again
else {
System.out.printf("%nHome\'s Insured Value: $%,.0f"
+ "%n%nIs this insured value correct? \'Y\' or \'N\': ",
homeInsVal);
correct = input.next().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of insured value
} while (repeat); //END do-while repeats when homeInsVal is not correct
}//END setHomeInsVal(): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setRichter() {
do {
do {
System.out.printf("%nRichter Scale Damage Assessment"
+ "%n 9.0+ Total destruction."
+ "%n 8.0 Most structures fell."
+ "%n 7.0 Many buildings destroyed."
+ "%n 6.0 Many buildings considerably damaged, some collapsed."
+ "%n 4.5 Damage to poorly constructed buildings."
+ "%n 3.5 Felt by many people, no destruction."
+ "%n 0 Generally not felt by people."
+ "%n%nPlease enter the Richter scale value for the earthquake: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when richter is invalid
richter = input.nextDouble();
if (richter < 0) {
System.out.printf("%nInvalid! Richter cannot be negative. Please re-enter.%n");
repeat = true;
}//END if richter less than zero then prompt again
else {
System.out.printf("%nRichter Scale: %.2f"
+ "%n%nIs this richter value correct? \'Y\' or \'N\': ",
richter);
correct = input.next().toLowerCase().charAt(0);
input.nextLine();
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of richter
} while (repeat); //END do-while repeats when homeInsVal is not correct
testRichter();
}//END setRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
private void testRichter() {
if (richter >= 9.0) {
payout = homeInsVal * .90;
deductible = homeInsVal * .10;
message = "Total destruction.";
}//END if richter >= 9.0 else richter < 9.0
else if (richter >= 8.0) {
payout = homeInsVal * .80;
deductible = homeInsVal * .20;
message = "Most structures fell.";
}//END if richter >= 8.0 else richter < 8.0
else if (richter >= 7.0) {
payout = homeInsVal * .70;
deductible = homeInsVal * .30;
message = "Many buildings destroyed.";
}//END if richter >= 7.0 else richter < 7.0
else if (richter >= 6.0) {
payout = homeInsVal * .60;
deductible = homeInsVal * .40;
message = "Many buildings considerably damaged, some collapsed.";
}//END if richter >= 6.0 else richter < 6.0
else if (richter >= 4.5) {
payout = homeInsVal * .50;
deductible = homeInsVal * .50;
message = "Damage to poorly constructed buildings.";
}//END if richter >= 4.5 else richter < 4.5
else if (richter >= 3.5) {
payout = 0;
deductible = 0;
message = "Felt by many people, no destruction.";
}//END if richter >= 3.5 else richter < 3.5
else if (richter >= 0) {
payout = 0;
deductible = 0;
message = "Generally not felt by people.";
}//END if richter >= 0 else richter < 0
}//END testRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getInsured() {
return insured;
}//END getInsured(): int
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getHomeInsVal() {
return homeInsVal;
}//END getHomeInsVal(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getRichter() {
return richter;
}//END getRichter(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getPayout() {
return payout;
}//END getPayout(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getDeductible() {
return deductible;
}//END getDeductible(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getMessage() {
return message;
}//END getMessage(): String
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void validateNumber() {
if (repeat) //AS LONG AS THE INPUT IS "NOT" AN INTEGER OR DOUBLE
{
input.next(); //CONSUME NON-NUMERIC VALUE.
System.out.printf("%nWarning: You entered an invalid integer or "
+ "floating-point value.%n"); //RE-PROMPT
}//END if repeat when a number is an invalid type
}//END validateNumber(boolean): void
/**
* chars() returns the integer values of the characters in word.
* <p>
* allMatch determines whether the integer values for each character
* matches the predicate (criterion) that each character is a letter.
* <p>
* The :: is a method reference operator for calling isLetter from
* the Character class.
*
* #param word is the incoming String value to test.
* #return is true when the word is not empty and is alphabetic
* or false when it isn't.
*/
public final boolean isAlpha(String word) {
/* Test to see if the word is not empty AND if each letter
* in a word is an alphabetic character.
*/
return word != null && word.chars().allMatch(Character::isLetter);
}//END isAlpha(String): final boolean
}//END CLASS EarthquakeInsurance
}
Mistake 1)
for ( EarthquakeInsurance eachClaim : claims);
remove semi
Mistake 2)
System.out.println(claims);
Yes you are print the whole list
See also How do I print my Java object without getting "SomeType#2f92e0f4"?
I'm writing a program to take in commands from the user, and output accordingly. The program keeps asking for input, until the user inputs "Quit" as a command.
Commands are:
Factorial # (takes one number as an argument)
Outputs the factorial of the number, Ex.
Factorial 5
5! == 120
GCD # # (Takes 2 numbers as arguments)
outputs the greatest common divisor between 2 numbers (Recursively.) Ex.
gcd 5 10
gcd(5, 10) == 5
Sorted # #... (Takes as many numbers as the user wants)
checks to see if the numbers after the command are in order. Ex.
sorted 1 2 3 4 5
That list is sorted.
sorted 1 2 3 5 4
Out of order: 4 after 5.
Now all this works pretty good. nothing wrong as of now, what im struggling with, when the user enters a letter instead of a number, it should try and catch an InputMismatchException, this kind of works. for example.
if the user enters a letter it would say this.
Factorial j
Not a number: For input string: j
BUT
Factorial 5 j
5! == 120
it would go on how it normally would, but it takes the "j" as the next command, for so if i type Factorial 5 quit, it would print the factorial then quit, i don't know why this is happening.
another thing is i want to throw and catch an exception if the arguments are too much for the command, so the user cant type Factorial 5 10, and it would just calculate the factorial of 5, it would print an error message, i dont know how to achieve this.
Heres my code as of now.
A09.java
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
*
*
* #author Amr Ghoneim (A00425709)
*
*/
public class A09 {
static int counter = 0;
#SuppressWarnings("resource")
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.next().toLowerCase();
// FACTORIAL
if (commands[1].startsWith(command)
&& commands[1].contains(command)) {
try {
int num = scnr.nextInt();
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// GCD
} else if (commands[2].startsWith(command)
&& commands[2].contains(command)) {
try {
int numA, numB;
numA = scnr.nextInt();
numB = scnr.nextInt();
System.out.println("gcd(" + numA + ", " + numB + ") == "
+ GCD(numA, numB));
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// SORTED
} else if (commands[0].startsWith(command)
&& commands[0].contains(command)) {
try {
List<Integer> nums = new ArrayList<Integer>();
StringTokenizer st = new StringTokenizer(scnr.nextLine(),
" ");
while (st.hasMoreTokens()) {
nums.add(Integer.parseInt(st.nextToken()));
}
sorted(nums);
} catch (NumberFormatException nfe) {
System.out.println("Not a number: For input string: ");
}
// QUIT
} else if (commands[4].startsWith(command)
&& commands[4].contains(command)) {
isValid = false;
quit();
// HELP
} else if (commands[3].startsWith(command)
&& commands[3].contains(command)) {
help();
}
}
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order"
+ "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)"
+ "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #"
+ "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of
them."
+ "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to
largest."
+ "\n If not, then where the first out-of-order number is."
+ "\n - help" + "\n This help message." + "\n - quit"
+ "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after "
+ nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}
What im missing is finding out how many arguments the user is putting, if too much print a message, and for the sorted command, i cant get it to print the letter the user puts. and for some reason when i input "Factorial 5 5" is would print the ">>>" twice instead of once. theres just some bugs here and there, can someone guide me on how i would approach this stuff, or show some examples?
Thanks!
I have modified your code so that it will work as what you have described. Just look at the code comments for details. Feel free to comment for clarifications.
Modified code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static int counter = 0;
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.nextLine().toLowerCase(); // instead of getting the input per space, get all the input per
// line
String[] userCommand = command.split(" "); // split the line by spaces
// check if the command has at least 2 parameters except for "help" and "quit"
if (!commands[3].equals(userCommand[0]) && !commands[4].equals(userCommand[0]) && userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
// since you know that the first word will be the command, you just have to get
// the value of index 0
// FACTORIAL
// use equals do not use startsWith or contains since it will hold true for
// inputs "FACTORIALINVALID 4"
if (commands[1].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 2 parameters
if (userCommand.length != 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the factorial and convert it into an int
int num = Integer.parseInt(userCommand[1]);
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// GCD
// use equals do not use startsWith or contains since it will hold true for
// inputs "GCDINVALID 4 5"
} else if (commands[2].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 3 parameters
if (userCommand.length != 3) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the GCD and convert it into an int
int numA, numB;
numA = Integer.parseInt(userCommand[1]);
numB = Integer.parseInt(userCommand[2]);
System.out.println("gcd(" + numA + ", " + numB + ") == " + GCD(numA, numB));
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// SORTED
// use equals do not use startsWith or contains since it will hold true for
// inputs "SORTEDINVALID 4 5 6"
} else if (commands[0].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must at least 2 parameters
if (userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
List<Integer> nums = new ArrayList<Integer>();
// get the list
for (int i = 1; i < userCommand.length; i++) {
nums.add(Integer.parseInt(userCommand[i]));
}
sorted(nums);
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// QUIT
// use equals do not use startsWith or contains since it will hold true for
// inputs "QUITINVALID"
} else if (commands[4].equals(userCommand[0])) {
isValid = false;
quit();
// HELP
// use equals do not use startsWith or contains since it will hold true for
// inputs "HELPINVALID"
} else if (commands[3].equals(userCommand[0])) {
help();
}
}
scnr.close();
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order" + "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)" + "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #" + "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of them." + "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to largest."
+ "\n If not, then where the first out-of-order number is." + "\n - help"
+ "\n This help message." + "\n - quit" + "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after " + nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}
I'm working on another assignment and am stuck. First off, I realize I probably won't get the results I want from this code, but at the moment I can't run the code to even see how close or far away I am. I'm sure I'm missing something simple and hope that something will pop out to someone here so I can move past this point. My mother tongue is English but I'm living in Sweden and trying to learn code in a Swedish class so I added //for translations.
Again, I am working with very basic code so am not looking for an easy hack, more of just some insight to where I have gone wrong.
My assignment is to ask the user to enter 10 numbers, store those as an array. Then, offer the user 4 options to calculate those numbers and a 5th option to quit the program.
Here's what I have so far:
package inlämningsuppgift3;
import java.util.Scanner;
import java.util.Arrays;
public class Inlämningsuppgift3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal = 0;
int[] num = new int[10];
int sum = 0;
int min = 0;
int max = 0;
for (nr = 0; nr < 10; nr++) {
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr] = tal;
if (nr == 0) { //first number
min = tal;
max = tal;
}
else { // All other numbers
if (tal > max) { max = tal; }
if (tal < min) { min = tal; }
}
sum = sum + tal;
}
{
// What would you like to do?
System.out.println("Välj vad du vill göra?");
// Show largest number
System.out.println("1: Visa storsta talet.");
// Show smallest number
System.out.println("2: Visa minsta talet.");
// Show average
System.out.println("3: Visa medeltalet.");
// Show all numbers
System.out.println("4: Visa alla inmatade tal.");
// Quit
System.out.println("5: Avsluta");
}
do {
int k = input.nextInt();
if (k == 1) {
// Largest number is:
System.out.println("Storsta talet är: " + max);
}
else if (k == 2) {
// Smallest number is:
System.out.println("Minsta talet är: " + min);
}
else if (k == 3) {
// Average number is:
System.out.println("Medeltalet är: " + sum/10);
}
else if (k == 4) {
// All the entered numbers:
System.out.println("Alla tal: " + num[10] + ", ");
}
else if (k==5) {
// Goodbye
System.out.println("Hej då!");
break;
}
else {
System.out.println("Felaktigt, prova igen.");
// Unrecognized, try again.
}
while (k<5);
}
}
}
I'm getting error on the last 3 } and I'm not sure why. Are they in the wrong place? I've tried moving them around, I've tried deleting them (obviously, didn't help either) I tried changes to my {} placement above in the code and just haven't found a way around this error. Thank you in advance for any input!
java do-while syntax is:
do {
// Statements
}while(Boolean_expression);
so, change it to:
int k = 0;
do {
k = input.nextInt();
if (k == 1) {
System.out.println("Storsta talet är: " + max);
} else if (k == 2) {
System.out.println("Minsta talet är: " + min);
} else if (k == 3) {
System.out.println("Medeltalet är: " + sum / 10);
} else if (k == 4) {
System.out.println("Alla tal: " + num[10] + ", ");
} else if (k == 5) {
System.out.println("Hej då!");//good bye
break;
} else {
System.out.println("Felaktigt, prova igen.");
}
} while (k < 5) ;
and after while line must be two } now.
Hej Hej!
I made the modifications I think like you asked to make it 'just about work'
package Dunno;
import java.util.Scanner;
public class NumberCollector { //No special characters in source files,
//Can get transformed during deployment
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal =0;
int[] num = new int[10];
int sum = 0;
int min=0;
int max=0;
for (nr=0; nr<10; nr++)
{
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr]=tal;
if(nr == 0) //first number
{
min=tal;
max=tal;
}
else //all other numbers
{
if(tal>max)max =tal;
if(tal<min) min=tal;
}
sum = sum + tal;
}
System.out.println("Välj vad du vill göra?");
//what would you like to do?
System.out.println("1: Visa storsta talet.");
//Show largest number
System.out.println("2: Visa minsta talet.");
//show smallest number
System.out.println("3: Visa medeltalet.");//show average
System.out.println("4: Visa alla inmatade tal.");
//show all numbers
System.out.println("5: Avsluta");//quit
while (true) //Moved the stop condition to start of the loop makes it easier to read logically.
{
int k = input.nextInt();
if (k==1)
{
System.out.println("Storsta talet är: " + max);
//largest number is:
}
else if (k==2)
{
System.out.println("Minsta talet är: " + min);
//smallest number is:
}
else if (k==3)
{
System.out.println("Medeltalet är: " + sum/10);
//average number is:
}
else if (k==4)
{
System.out.println("Alla tal: " + num[10] + ", ");
//all the entered numbers:
}
else if (k==5)
{
System.out.println("Hej då!");//good bye
break;
}
else
{
System.out.println("Felaktigt, prova igen.");
//unrecognized, try again.
}
};
}
}
I only had to move around some braces.
It seems to broadly do what you want? It throws an exception if you ask for result 4, I'll leave that to you :)
Maybe this will be a good starting point? Consider replacing the loop with a switch/case condition would be nicer to read and maintain?
I am having trouble writing code that will execute through the one loop while it is odd and through another loop if it is even. Here is my code so far:
public class Sequence {
public static void main(String args[]) {
System.out.println("Please Enter an positive integer no more than 100: ");
Scanner input = new Scanner(System.in);
int initial = input.nextInt();
if (initial >= 100 || initial <= 0) {
System.out.println("The input is invalid");
}
if (initial % 2 == 0) {
while (initial % 2 == 0) {
System.out.print("[" + initial + "] ");
initial = initial / 2;
}
}
if (initial % 2 == 1) {
while (initial % 2 == 1) {
System.out.print("(" + initial + ") ");
initial = 6 * initial + 2;
}
}
}
}
Hope this code will help your need
private static int handleOddNo(int oddNo){
int initial = oddNo;
while (initial % 2 == 1) {
System.out.print("(" + initial + ") ");
initial = 6 * initial + 2;
if(initial == 1)
break;
}
return initial;
}
private static int handleEvenNo(int evenNo){
int initial = evenNo;
while (initial % 2 == 0) {
System.out.print("[" + initial + "] ");
initial = initial / 2;
if(initial == 1)
break;
}
return initial;
}
public static void main(String args[]) {
System.out.println("Welcome to The Sequence Generator");
System.out.println("---------------------------------");
System.out.println("Please Enter an positive integer no more than 100: ");
Scanner input = new Scanner(System.in);
int initial = input.nextInt();
if (initial >= 100 || initial <= 0) {
System.out.println("The input is invalid");
}
do{
if (initial % 2 == 0) {
initial = handleEvenNo(initial);
}else{
initial = handleOddNo(initial);
}
}while(initial != 1);
}
The problem can be illustrated with 5 as an input. Since this is odd, you completely skip the even case and then continue to calculate 6 * 5 + 2 which is 32. I assume that you now want to treat return to the even case and continue calculating. Note that this implies that you need a loop. In other words, you should put an if statement inside a while loop. Your current logic is the exact reverse of this.
First of all, I apologize because this code seems inefficient to me, but my professor wants it this way (the comments are hers). I have many problems here, but a central one seems to be that when I run the program it does not enter the for loop. Therefore I'm assuming it is not entering the while loop that the for loop is in, and I'm not sure why. Here is the "modified" blackjack program, any help is appreciated:
import java.util.Scanner;
import java.util.Random;
public class BlackJack {
enum Decisions
{
HIT, STAND, SURRENDER, QUIT, PLAY, NOTVALID;
// NOTVALID is used to re-ask to play again
}
enum Card {
ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, QUEEN, JACK, KING;
}
// Tells you if the Decision enum is valid or not
public static boolean containsDecision(String decision) {
for (Decisions d : Decisions.values()) {
if (d.name().equals(decision)) {
return true;
}
}
return false;
}
// Tells you what is the integer value of said Card enum
public static int getCardValue(int pick) {
if (pick == 0) {
return 1;
} else if (pick >= 10 && pick <= 12) {
return 10;
}
return pick + 1;
}
// 1 pts
public static int housePlay(int houseCardSum) {
int cardPick;
cardPick = -1;
while (houseCardSum <= 17)
{
getCardValue(cardPick);
houseCardSum = (cardPick + houseCardSum);
System.out.println("Hit from house! CARD: " + cardPick + " VALUE: " + houseCardSum);
}
return houseCardSum;
}
// 1.5 pts
public static void findWinner(int playerCardSum, int houseCardSum, Decisions decision) {
houseCardSum = housePlay(houseCardSum);
if ( (playerCardSum > 21) || (houseCardSum > 21))
{
if (houseCardSum > 21)
{
System.out.println("Sorry you lose!");
}
else
{
System.out.println("You win!");
}
}
else if (decision == Decisions.SURRENDER)
{
System.out.println("You lose because you surrendered!");
}
else if (playerCardSum == houseCardSum)
{
System.out.println("Its a push (tie)!");
}
else if ((playerCardSum > houseCardSum) && (playerCardSum < 21))
{
System.out.println("You win!");
}
else if ( (playerCardSum == 21) && (houseCardSum != 21) )
{
System.out.println("Blackjack win!");
}
else
{
System.out.println("Sorry you lose!");
}
// if, else if, else, check playerCardSum, houseCardSum as well as if
// Decision equaled to SURRENDER
// print the House and You Hand at the end
// call housePlay function and assign the output to houseCard function
// iff not playerCardSum is not 21 and Decisions is not Surrender
// these below will be used moved them around freely in this function
// where you need too.
// put in correct branch sub
// statement
System.out.println("House Hand: " + houseCardSum + " Your Hand: " + playerCardSum); // this
// is
// printed
// out
// after
// all
// branch
// statements
// assessed
}
// 7.5pts
public static void main(String[] args) {
System.out.println("========== BlackJack ==========");
System.out.print("What is your name: ");
Scanner keyboard = new Scanner(System.in);
String playerName;
playerName = keyboard.nextLine();
System.out.println("Okay, " + playerName + ", let's play!");
Decisions decision = Decisions.PLAY ;
int cardPick;
cardPick = -1;
while ( decision != Decisions.QUIT);
{
int playerSum;
int houseSum;
playerSum = 0;
houseSum = 0;
Card holeCard = null;
for ( int i = 0; i < 3; i++)
{
Random newCard = new Random();
cardPick = newCard.nextInt(14);
playerSum = playerSum + getCardValue(cardPick);
System.out.println("Card: " + (Card.values()[cardPick]) );
System.out.println("Sum of your hand: " + playerSum );
}
}
Remove the semicolon after the while statement.
while ( decision != Decisions.QUIT);
while ( decision != Decisions.QUIT)