I am very close to finishing my task, but I can't figure out how to call findChange() correctly. My guess is that it needs to be in the main method. But when findChange(); call it, it asks for int, List<Integer>, List<Integer> so how do I do this "correctly" so to speak.
CODE
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int change;
public static void main(String[] args)
throws FileNotFoundException
{ //begin main
ArrayList<Integer> coinTypes = new ArrayList<Integer>();//array to store
//coin types
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f); //initialize scanner
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1); //this will add all ints
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
//findChange(); ideal spot to call the method
//System.out.println(coinTypes);
}
boolean findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins)
{ //contains means of
//finding the change solutions
if(change == 0) {
return true; //a solution
}
if(change < 0) {
return false; //if negative it can't be a solution
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin); //if it works out add it to the
return true; //solution List
}
}
}
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) { //if there is a solution, print it
System.out.println(answer);
} else { System.out.println("No change found");
}
return false; //else return false
}
}
This program calculates all the different ways to show change for a certain amount of money ie: 143 ($1.43). All I gotta do is call findChange() to main and it should work, what am I missing?
EDIT I just realized I didn't specify the method call I need help with I apologize for any unclearness
INPUT FILE
// Coins available in the USA, given in cents. Change for $0.09?
1 5
9
CURRENT OUTPUT
Change: 9
WANT
Change: 9
['solutions to all possible combinations to make $0.09']
Related
I wanted to make an input which accepts numbers from 1 - 10 and prints the range.
I need to check if the input is an integer (check), check if the range is 0-10 (check), and if it's not any of those things, to ask the user again. So, a recursive method?
Currently I have this:
import java.util.Scanner;
import java.util.InputMismatchException;
public class FinalTest {
public static void main (String [] args) {
Scanner in = new Scanner(System.in);
int k = 0;
System.out.print("int - ");
try {
k = in.nextInt();
} catch (InputMismatchException e) {
System.out.println("ERR: Input");
System.exit(1);
}
if(k <= 10 && k > 0) {
for(int j=1; j <= k; j++) {
System.out.println(j);
}
} else {
System.out.println("ERR: Oob");
System.exit(1);
}
}
}
I would like to replace the "System.exit()" so that it re attempts to ask the user for input again.
calling main(); produces an error.
How do I correctly call the main method in this case?
Two choices here:
actually create a method and call that
simply use a loop
Loop could go like:
boolean askForInput = true;
while ( askForInput ) {
try {
k = in.nextInt();
askForInput = false;
} catch ...
print "not a number try again"
}
But beyond that: you still want to put this code into its own method. Not because that code should call itself, but for clarity reasons. Like:
public static int askForNumber(Scanner in) {
... code from above
return k;
}
And to answer your question: you do not want to use recursion here. You want to loop; and yes, recursion is one way to implement looping, but that is simply overkill given the requirement you want to implement here.
And for the record: when creating that helper method, you can actually simplify it to:
public static int askForNumber() {
while ( askForInput ) {
try ...
return in.nextInt();
} catch ...
print "not a number try again"
}
}
Beyond that: you typically use recursion for computational tasks, such as computing a factorial, or fibonacci number, ... see here for example.
for the part of the recursive method printing a range:
public void printAscending(int n) {
if (n > 0) {
printAscending(n - 1);
System.out.println(n);
}
}
I think using recursion is just too much for something that simple and would probably be more expensive. You can add a while loop around your scanning bit until the entered value is valid. I would also put the printing loop out of the while to not have to test a condition before printing since if you get out of the while loop, it means number if valid. You could test just the -1 value to exit process.
public class FinalTest
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int k = 0;
do
{
System.out.print("int - ");
try
{
k = in.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("ERR: Input");
System.exit(1);
}
}
while(!(k>0 && k<=10) && k!=-1);
if(k!=-1)
{
for(int j=1; j<=k; j++)
{
System.out.println(j);
}
}
else
{
System.out.println("Bye Bye.");
}
}
}
Okay, so what I personally do when I need to use recursion is I create a separate function/method for it. And when I need to restart the method, I just call it within itself. So it would be something like this:
private void recursiveMethod() {
// do stuff . . .
if (yourCondition) {
//continue to next piece of code
} else {
recursiveMethod();
}
}
But in big projects, try to stay away from recursion because if you mess up, it can
The purpose of this project is to make a pokedex that adds and holds all the pokemon passed in by user input. When the user inputs a pokemon that is already stored in the pokedex the word "duplicate" is supposed to be printed to the console. The word duplicate is printed even though there are no actual duplicates within the object array. Here is my output from the console :
Welcome to your new PokeDex!
How many Pokemon are in your region?: 3
Your new Pokedex can hold 3 Pokemon. Let's start using it!
List Pokemon
Add Pokemon
Check a Pokemon's Stats
Sort Pokemon
Exit
What would you like to do? 2
Please enter the Pokemon's Species: red
Duplicate
Now here is all the code used that could possibly be making this error
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to your new PokeDex!");
System.out.print("How many Pokemon are in your region?: ");
int size = input.nextInt();
Pokedex pokedex = new Pokedex(size);
System.out.println("\nYour new Pokedex can hold " + size + " Pokemon. Let's start using it!");
int choice = 0;
boolean done = false;
while (!done) {
System.out.println("\n1. List Pokemon\n2. Add Pokemon\n3. Check a Pokemon's Stats" + "\n4. Sort Pokemon\n5. Exit");
System.out.print("\nWhat would you like to do? ");
choice = input.nextInt();
switch (choice) {
case 1:
String[] pokemonList = pokedex.listPokemon();
if (pokemonList == null)
System.out.println("Empty");
else
for (int i = 0; i < pokemonList.length; i++) {
System.out.println((i + 1) + ". " + pokemonList[i]);
}
break;
case 2:
System.out.print("\nPlease enter the Pokemon's Species: ");
String species = input.next();
pokedex.addPokemon(species);
break;
}
}
}
}
In the following class I have the actual method that adds the pokemon and the constructor for Pokedex
public class Pokedex {
Pokemon[] pokedex;
String pokeArray[];
public Pokedex(int size) {
pokedex = new Pokemon[size];
pokeArray = new String[size];
}
public boolean addPokemon(String species) {
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++) {
if (pokedex[i] == null) {
pokedex[i] = stuff;
}
else if (i < pokedex.length && pokedex[i] != null) {
System.out.println("Max");
}
if (pokedex[i].getSpecies().equalsIgnoreCase(species)) {
System.out.print("Duplicate");
break;
}
}
return false;
}
}
Sorry for the mass amounts of code I just need help tracing where this unexpected result is coming from.
The reason it's doing that is because of this bit of code here:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if (pokedex[i] == null)
pokedex[i] = stuff;
else if (i < pokedex.length && pokedex[i] !=null)
System.out.println("Max");
if(pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.print("Duplicate");
break;
}
}
return false;
}
The problem is just a little bit of syntax missing. In your for loop, you check to see if
A) there are any empty spots in the array
B) if every element in the array up to the user inputted size is full
and C) if any element in the array matches the one we're trying to add.
The problem you're encountering is because your C is an if instead of an else if. Because A sees the index is null, it assigns the new Pokemon to the Pokedex. Then because C is an if instead of an else if, it runs after you assign the new Pokemon and sees the Pokemon we just added and says it's a duplicate. Changing it to an else if would fix this.
Also, since there was no break; in A, it would assign every element of the array to the first one entered, causing any further additions to call Max. I edited the code and this is what I had that worked for me:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if(pokedex[i] !=null && pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.println("Duplicate");
break;
}
else if (pokedex[i] == null)
{
pokedex[i] = stuff;
break;
}
else if(i + 1 == pokedex.length)
{
System.out.println("Max");
break;
}
}
return false;
}
Also, out of curiosity, why is the addPokemon() function a boolean? You return a value (albeit arbitrarily) and then never do anything with that value. You could just make it a void, have it return nothing, and it would work just as fine.
I was recently trying to build a program that takes two inputs and checks whether they are equally represented in other bases(bases are up till 20). But i keep getting the index out of bounds exception at line number 28...what to do?
For example: 12(base 10) = 5(base 3) [both are represented as '12' in their respective bases.]
import java.util.Scanner;
import java.util.Arrays;
class Bases
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Two Numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Thank You for inputting the numbers!");
String basea[] = new String[20];
String baseb[] = new String[20];
int i=0 , j=0;
for( i=0;i<20;i++)
{
basea[i] = convert(a,i+1);
baseb[i] = convert(b,i+1);
}
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
if(i!=20){
if(i==0){
i=9;
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else System.out.println("Numbers dont match at all till base 20!!");
}
private static String convert(int number,int base)
{
return Integer.toString(number,base);
}
}
for(j=0;i<=19;j++)
This above loop should be j <= 19
for(j=0;j<=19;j++)
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
You can see in this original snippet of code you had a typo
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++) <---- the middle parameter is 'i' instead of 'j'
{
Simply fix this by fixing your typo, and if you want to you can make it <20 for some added neatness.
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
I am trying to execute a program after taking user input from the console. [code block below]. However, I do not want to terminate after the program execution finishes. I want the console to always ask me the INITIAL_MESSAGE after the execution finishes. Effectively, after the execution of the program, I want the console to again ask me the INTIAL_MESSAGE so that I can again enter the inputs as I want and execute the program again.
I am actually calling the interactor() in this method, from the main method as the starting point.
Please tell me how do I achieve this
public class ConsoleInteraction {
/**
* #param args
*/
public static int numberOfJavaTrainees ;
public static int numberOfPHPTrainees ;
Barracks trainingBarrack = new Barracks();
public void interactor() throws IOException {
//reading capability from the consolemessages properties file
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
// Create a scanner so we can read the command-line input
Scanner scanner = new Scanner(System.in);
// Prompt for training or viewing camp
System.out.print(bundle.getString("INITIAL_MESSAGE"));
//Get the preference as an integer
int preference = scanner.nextInt();
//Show options based on preference
if(preference == 1)
{
//System.out.println("Whom do you want to train?\n 1.Java Guy \n 2.PHP Guy \n 3.Mix \n Enter You preference:");
System.out.print(bundle.getString("WHO_TO_TRAIN"));
int traineepreference = scanner.nextInt();
if (traineepreference == 1)
{
//System.out.println("How many Java guys you want to train ? : ");
System.out.print(bundle.getString("HOW_MANY_JAVA"));
numberOfJavaTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(numberOfJavaTrainees, 0);
}
else if (traineepreference == 2)
{
//System.out.println("How many PHP guys you want to train ? : ");
System.out.print(bundle.getString("HOW_MANY_PHP"));
numberOfPHPTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(0, numberOfPHPTrainees);
}
else if (traineepreference == 3)
{
System.out.print(bundle.getString("HOW_MANY_JAVA"));
numberOfJavaTrainees = scanner.nextInt();
System.out.print(bundle.getString("HOW_MANY_PHP"));
numberOfPHPTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(numberOfJavaTrainees, numberOfPHPTrainees);
}
else
{
System.out.print(bundle.getString("ERROR_MESSAGE1"));
}
}
else if (preference == 2)
{
System.out.println("Showing Camp to You");
System.out.println("Java trained in Trainee Camp : "+ TraineeCamp.trainedJavaGuys);
System.out.println("PHP trained in Trainee Camp : "+ TraineeCamp.trainedPHPGuys);
}
else
{
System.out.print(bundle.getString("ERROR_MESSAGE2"));
}
scanner.close();
}
}
Consider these changes quickly drafted to your class. Might not compile. Might not work as you planned.
Some highlights of what I think you should change:
Use constants for the choice values. Makes your code way more better to read.
Initialize Bundle and Scanner outside of the method. Might be reused.
instead of coding lengthy parts of code inside of the if-else-if cascade, call methods there - angain increasing your readability a long way
public class ConsoleInteraction {
public static int numberOfJavaTrainees ;
public static int numberOfPHPTrainees ;
//Don't read that every time...
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
public static void main(String[] args) {
//Moving Scanner out of loop
try {
Scanner scanner = new Scanner(System.in);
ConsoleInteraction ci = new ConsoleInteraction();
//Loop until this returns false
while(ci.interactor(scanner)) {
System.out.println("=== Next iteration ===");
}
} catch (IOException e) {
e.printStackTrace();
}
}
//Constant values to make code readable
public final static int PREF_TRAINING = 1;
public final static int PREF_SHOW_CAMP = 2;
public final static int PREF_QUIT = 99;
public boolean interactor(Scanner scanner) throws IOException {
// Prompt for training or viewing camp
System.out.print(bundle.getString("INITIAL_MESSAGE"));
//Get the preference as an integer
int preference = scanner.nextInt();
//Show options based on preference.
if(preference == PREF_TRAINING) {
//LIKE YOU DID BEFORE OR calling method:
readTraining(scanner);
} else if (preference == PREF_SHOW_CAMP) {
//LIKE YOU DID BEFORE OR calling mathod:
showCamp();
} else if (preference == PREF_QUIT) {
//Last loop
return false;
} else {
System.out.print(bundle.getString("ERROR_MESSAGE2"));
}
//Next loop
return true;
}
}
I'm trying to figure out why 1) my Simon game hangs up after saying "Enter A Number"- it doesn't look like it even gets past validation. I'm trying to get user input, and check to see if that was the right number to press at that time. 2) Also, it used to generate a random number but when the user pressed it, it came back as false for some reason. Some other random number would pass though. 3) Also, is the code below color coded for you? Thanks guys.
import acm.program.*;
import acm.graphics.*;
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.DataInputStream;
public class Simon extends Program implements ActionListener
{
Scanner usersInputScanner = new Scanner(System.in);
private int array[];
private int currentSeqLength;
private int usersInput;
private String usersInputString;
public Simon()
{
//Initialize Class Values
array = new int[20];
currentSeqLength = 1;
usersInput = 0;
generateSequence();
while(currentSeqLength < array.length)
{
playSequence();
//Wait For User's Input, Assign To Variable
System.out.println("Enter A Number");
usersInput = usersInputScanner.nextInt();
if (pushButton(usersInput) == true)
{
System.out.println("You Entered: " + usersInput);
currentSeqLength++;
}
else
{
gameOverMessage();
break;
//Reset Variables:
}
}
}
//----------------------- Methods Here On Down -----------------------------
public void generateSequence()
{
//Fill Array With Random Numbers
for (int i = 0; i < array.length; i++ )
{
array[i] = (int)(Math.random()*4);
}
}
public void setLength(int length)
{
//Set Current Length To Size Of Given Argument
currentSeqLength = length;
}
int getLength()
{
return currentSeqLength;
}
int[] playSequence()
{
//Print Out The Current Sequence
//New Local Array To Return
int newArray[]= new int[currentSeqLength];
//Repeat As Many Times As Value Of currentSeqLength
for(int i = 0; i < currentSeqLength ; i++)
{
System.out.println(array[i]);
//Return an array of int's to the player.
newArray[i] = array[i];
}
return newArray;
}
boolean pushButton(int usersInput)
{
//Given A Button Press (0-3), Return Whether That Was The
//Correct Button To Play At The Moment
if (usersInput == array[currentSeqLength])
{
return true;
}
else
{
return false;
}
}
boolean isTurnOver()
{
//If Current Sequence Length Matches Or Exceeds Value Of
//Array Element In Location Of Current Sequence Length
if (currentSeqLength >= array[currentSeqLength])
{
return true;
}
else
{
return false;
}
}
//Not Needed?
boolean isGameOver()
{
if (pushButton(usersInput) == false)
{
return true;
}
else
{
return false;
}
}
String gameOverMessage()
{
return "Game Over";
}
/*public void actionPerformed(ActionEvent event)
{
int input;
}
*/
}
1) my Simon game hangs up after saying "Enter A Number"- it doesn't
look like it even gets past validation.
It's working fine, but you need to System.out.println the string that is returned from gameOverMessage(). Right now, it runs perfectly but there's no output to the console, so it looks unresponsive (and it's not hanging, it just reaches the end of execution, and stops).
else {
gameOverMessage();
break;
}
should be
else {
System.out.println(gameOverMessage());
}
2) Also, it used to generate a random number but when the user pressed
it, it came back as false for some reason.
I'm not getting this behavior in your sample code, it looks like it works as expected.
3) Also, is the code below color coded for you?
Yep, the preview box on SO sometimes takes a second to do the syntax highlighting. It works fine though.
Incidentally, 3 questions in one is a bit of a slog for the answerer. In the future perhaps try to limit yourself to one :)