Debugging School Project - java

Right, I am working on a program for school the purpose of the program is to find the minimum number of coins, I am a novice programmer and this is my first time so I dont know the thousands of other things and what not other people do. I wrote the code and it works, but I seem to have found a bug/glitch or w/e you want to call it.
my code
import java.util.Scanner;
public class Coin {
public static void main (String[] Args) {
int quarters = 25;
int dimes = 10;
int nickles = 5;
int pennies = 1;
System.out.println("Enter in a number between 1-99");
// "Input" Part of Code (Remember this and go back for reference)
Scanner Userinput = new Scanner(System.in);
int stuff = Userinput.nextInt();
int q = stuff/quarters;
String A = "Number of Quarters:" +q;
System.out.println(A);
int hold = stuff%quarters;
int d = hold/dimes;
String B = "Number of Dimes:" +d;
System.out.println(B);
int hold1 = stuff%dimes;
int n = hold1/nickles;
String C = "Number of Nickles:" +n;
System.out.println(C);
int hold2 = stuff%nickles;
int p = hold2/pennies;
String D = "Number of Pennies:" +p;
System.out.println(D);
System.out.println("Thank you for Using My Program");
}
}
Now, everything works fine I can input any number I like and get the desired result, however for some odd reason I cannot fathom I type in any number between 75-79 and there is an added Nickle for some odd reason and I have spent the better part of 2 hours trying to figure out exactly what is wrong but cannot. Hav tried dozens of toher numbers and they work fine except for that one little area.
Can someone tell me by chance what might be wrong?

Your hold = ... lines should be based on the previous hold value rather than the full amount (stuff).
int hold2 = hold%nickles;

You need to subtract off what has already been accounted for when adding previous, larger coins.
For example, if I say 77, then the program will check 77%10 and return 7. You would want to adjust your "stuff" value by any previously added coins. So in this case, after adding 3 quarters (75) we would want to set stuff = stuff - 75 (stuff -= 75).
EDIT: to be more precise, after every calculation you could run
stuff -= q * quarters;
of course, changing the variables to be appropriate for each part of your code.

Related

why can int not be deferenced?

I'm writing a while loop program and this problem keeps staying here and I'm not sure how to fix it. Keeps displaying "int cannot be dereferenced". I have done a ton of research on this problem and I don't know what am I doing wrong: read on google, read on StackOverflow and so on, but I don't know what to do. Tried the parsing technique but kept saying "scanner cannot convert string to int" Here is my code, any help would be appreciated. I could have declared the variable in the if and else if conditions, but I would like to keep track of what I am doing and I believe it's better to not repeat codes. (such as print out statement)
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner Data = new Scanner (System.in);
final int goldplated = 100, fourteen = 500, eighteen = 1000;
int total = 0, count = 1, size = 0;
String GetInfo = "";
System.out.println("How many times do you want to purchase:");
int EnterData = Data.nextInt();
while(count<=EnterData){
System.out.println("What Kind of Chain do you want to buy? Below are the list of options: \n 1 - gold plated \n 2 - 14k gold \n 3 - 18k gold");
//GetInfo = Data.next();
if (Data.equals("1")||Data.equals("gold plated")){
System.out.println("Please specify the length of the chain.");
size.nextInt();
total = size * goldplated;
}else if(Data.equals("2")||Data.equals("14k gold")){
System.out.println("Please specify the length of the chain.");
size.nextInt();
total = size * fourteen;
}else if(Data.equals("3")||Data.equals("18k gold")){
System.out.println("Please specify the length of the chain.");
size.nextInt();
total = size * eighteen;
}else{
System.out.println("Invalid operation");
} count++;
total+= size.nextInt();
System.out.println("This is your price: " + total);
}
}
}
nextInt() is a method in the Scanner class. So when you write something.nextInt(), the something part will have to be a Scanner object. And in your case, you've got a Scanner object, which you've called Data (not the best name for it, but never mind).
If you write Data.nextInt(), your program will wait for the user to type in a number, and return that number. That's what you want, but you'll want a variable to assign that number to, so that you can use it. That variable is size. So every time you've written size.nextInt(); in your program, what you actually need to write instead is size = Data.nextInt(); - that is, call the method on the Data object, and assign the result to the size variable.

A random number with 3 digit and try to guess every digit one by one

I am new in Java and for the moment basic with methods, classes and constructors. For practice I am trying to write a basic game (safecracker). So my logic is get a 3 digit random number and try to guess it.
private static int takeRandomSafeCode(int min, int max) {
Random random = new Random();
int result = random.nextInt(max - min) + min;
return result;
private static void playGame() {
int safeCode = takeRandomSafeCode(100, 999);
int guess = takeGuess();
These are my random number methods. But if player guess a number and first digit is correct but on a wrong place I want to say "1 digit is correct but on a wrong position" or if one digit is correct "1 digit is correct and correct position"
I need to use here if-else statement i guess but I get my numbers int variable. What is the way of checking numbers one by one? Do I need to use a String? I am a little bit lost at this point. I would appreciate with your help.
It may be preferable - and result in simpler code - if you generate an integer array with three elements. Logically, the safe code 1-2-3 is not one hundred and twenty three but actually 1 followed by 2 followed by 3.
private static int takeRandomDigit() {
Random random = new Random();
int result = random.nextInt(10);
return result;
}
private static void playGame() {
int[] safeCode = {takeRandomDigit(), takeRandomDigit(), takeRandomDigit()};
int guess = takeGuess();
for (int safeDigit : safeCode) // for each digit in the safe code
{
// if the digit matches the guess, do something
}
}
You can use some math to take the numbers for example if your number is:
d=253
d % 10 -> gives you 3
d / 10 % 10 -> gives you 5
d / 100 -> gives you 2
Changing it to string is also an option because you can then access the different characters using the string functions like charAt etc.
But if you want to make it the Java and OOP way in order to learn you can make an object and add the 3 numbers as properties of that object and input some of the logic for checking there instead of doing some magic tricks like the above. For example:
class Combination {
private int firstPos;
private int secondPos;
private int thirdPos;
public Combination(){
firstPos=random.nextInt(10);
secondPos=random.nextInt(10);
thirdPos=random.nextInt(10);
}
public boolean checkCombination(Combination testedCombination){
.............
}
some methods, getter, setters etc
}

Java: Saving User Input to be Calculated in a Loop

Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?
Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);
You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}
You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}
// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);

Calculate Dice Roll from Text Field

QUESTION:
How can I read the string "d6+2-d4" so that each d# will randomly generate a number within the parameter of the dice roll?
CLARIFIER:
I want to read a string and have it so when a d# appears, it will randomly generate a number such as to simulate a dice roll. Then, add up all the rolls and numbers to get a total. Much like how Roll20 does with their /roll command for an example. If !clarifying {lstThen.add("look at the Roll20 and play with the /roll command to understand it")} else if !understandStill {lstThen.add("I do not know what to say, someone else could try explaining it better...")}
Info:
I was making a Java program for Dungeons and Dragons, only to find that I have come across a problem in figuring out how to calculate the user input: I do not know how to evaluate a string such as this.
I theorize that I may need Java's eval at the end. I do know what I want to happen/have a theory on how to execute (this is more so PseudoCode than Java):
Random rand = new Random();
int i = 0;
String toEval;
String char;
String roll = txtField.getText();
while (i<roll.length) {
check if character at i position is a d, then highlight the numbers
after d until it comes to a special character/!aNumber
// so if d was found before 100, it will then highlight 100 and stop
// if the character is a symbol or the end of the string
if d appears {
char = rand.nextInt(#);
i + #'s of places;
// so when i++ occurs, it will move past whatever d# was in case
// d# was something like d100, d12, or d5291
} else {
char = roll.length[i];
}
toEval = toEval + char;
i++;
}
perform evaluation method on toEval to get a resulting number
list.add(roll + " = " + evaluated toEval);
EDIT:
With weston's help, I have honed in on what is likely needed, using a splitter with an array, it can detect certain symbols and add it into a list. However, it is my fault for not clarifying on what else was needed. The pseudocode above doesn't helpfully so this is what else I need to figure out.
roll.split("(+-/*^)");
As this part is what is also tripping me up. Should I make splits where there are numbers too? So an equation like:
String[] numbers = roll.split("(+-/*^)");
String[] symbols = roll.split("1234567890d")
// Rough idea for long way
loop statement {
loop to check for parentheses {
set operation to be done first
}
if symbol {
loop for symbol check {
perform operations
}}} // ending this since it looks like a bad way to do it...
// Better idea, originally thought up today (5/11/15)
int val[];
int re = 1;
loop {
if (list[i].containsIgnoreCase(d)) {
val[]=list[i].splitIgnoreCase("d");
list[i] = 0;
while (re <= val[0]) {
list[i] = list[i] + (rand.nextInt(val[1]) + 1);
re++;
}
}
}
// then create a string out of list[]/numbers[] and put together with
// symbols[] and use Java's evaluator for the String
wenton had it, it just seemed like it wasn't doing it for me (until I realised I wasn't specific on what I wanted) so basically to update, the string I want evaluated is (I know it's a little unorthodox, but it's to make a point; I also hope this clarifies even further of what is needed to make it work):
(3d12^d2-2)+d4(2*d4/d2)
From reading this, you may see the spots that I do not know how to perform very well... But that is why I am asking all you lovely, smart programmers out there! I hope I asked this clearly enough and thank you for your time :3
The trick with any programming problem is to break it up and write a method for each part, so below I have a method for rolling one dice, which is called by the one for rolling many.
private Random rand = new Random();
/**
* #param roll can be a multipart roll which is run and added up. e.g. d6+2-d4
*/
public int multiPartRoll(String roll) {
String[] parts = roll.split("(?=[+-])"); //split by +-, keeping them
int total = 0;
for (String partOfRoll : parts) { //roll each dice specified
total += singleRoll(partOfRoll);
}
return total;
}
/**
* #param roll can be fixed value, examples -1, +2, 15 or a dice to roll
* d6, +d20 -d100
*/
public int singleRoll(String roll) {
int di = roll.indexOf('d');
if (di == -1) //case where has no 'd'
return Integer.parseInt(roll);
int diceSize = Integer.parseInt(roll.substring(di + 1)); //value of string after 'd'
int result = rand.nextInt(diceSize) + 1; //roll the dice
if (roll.startsWith("-")) //negate if nessasary
result = -result;
return result;
}

multiple while loop comparison (BigDecimal and > 10 )

This is my first post and I have been searching google and stack overflow for the past 24 hours and can not seem to pin down my problem.
I am creating a simple square root program. For the input section I start a 'while' loop. I need it to compare two conditions.
1. is the input a number
2. is the input a number over ten.
I was successful in creating the original program, however I ran into a small problem while debugging. When I put in a vary large decimal or number I would get a run time error.
I discovered that I could use BigDecimal() to solve this problem.
However I am now running into a logic error that I cannot solve no matter how many times I search the internet.
The two conditions that I use in the while loop are:
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
This will make sure that there is a BigDecimal, but will not make sure that the input number is over ten.
Here is the whole program
import java.math.BigDecimal;
import java.util.Scanner;
/**
#author Mike
*/
public class SquareRootingWithoutBigDecimal
{
public static void main( String [] args )
{
Scanner scan = new Scanner(System.in);
double inputNumber = 0.00;
double rootedNumber = inputNumber;
BigDecimal inputNumberBig = new BigDecimal(0.00);
BigDecimal SENTINAL = new BigDecimal(10.00);
String garbage;
double garbageD = 0.00;
System.out.println("Please Enter a number to be Square rooted"
+ "\nThe number must be 10 or greater ");
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
{
garbage = scan.nextLine();
System.out.println("Please Enter a number to be Square rooted"
+ "\nThe number must be 10 or greater ");
}
inputNumberBig = scan.nextBigDecimal();
inputNumber = inputNumberBig.doubleValue();
rootedNumber = inputNumber;
do
{
rootedNumber = Math.sqrt(rootedNumber);
System.out.println(rootedNumber);
} while (rootedNumber >= 1.01 );
}
Any and all help is much appreciated.
-Mike
inputNumberBig = scan.nextBigDecimal();
inputNumber = inputNumberBig.doubleValue();
These HAVE to go before you while loop for your logic to work.
Also,
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
I could see this causing a problem. You should use && instead of ||

Categories

Resources