Java Adding Numbers Together + Score? - numbers

Hi I have made this to add to a score systems.
public int Cascore = 0;
public int Dascore = 0;
public int dascore () {
return Dscore = + 5;
}
public int cascore () {
return Cscore = + 3;
}
public int ddascore () {
return Dscore = + 1;
}
I call these methods dascore() cascore() during points in the code that add to the score system but the overall Dascore and Cascore seem to just be 3 or 5.
System.out.println("Bad Score: " + Dscore);
System.out.println("Good Score: " + Cscore);
Just out puts 5 & 3. When it should be something like 160/130...?

Let's try :
Dscore += 5
not =+

It looks like you wanted to this instead
public int Cascore = 0;
public int Dascore = 0;
public int dascore () {
return Dscore += 5;
}
public int cascore () {
return Cscore += 3;
}
public int ddascore () {
return Dscore += 1;
}

This isn't working because you aren't writing the correct code. Well, your IDE should generate an error...
There is nothing like the following in java!
= +
Java, as other language do, supports +=
Even + = is wrong too in java. Because there can't be a space between these two operators.
public int Cascore = 0;
public int Dascore = 0;
public int dascore () {
return Dscore += 5;
}
public int cascore () {
return Cscore += 3;
}
public int ddascore () {
return Dscore += 1;
}
For better understandability, Until you are using a Constant, don't start your variable name with an upper case letter.

Related

Backtrack the difference between these two codes

I have been trying to play around with backtracking. From my understanding these two codes are doing same thing but somehow I got different outcomes.
I am just trying to use some type of template to start with.
cout<<i<<endl;
backtrack(i+1);
backtrack(i+1);
and
for(int i=start; i<n; i++){
cout<<i<<endl;
backtrack(i+1);
}
The first one gets 5 as outcome and the second one gets six when I have the input of
nums=[1,1,1,1,1]
target = 3
public class Solution {
int count = 0;
public int findTargetSumWays(int[] nums, int S) {
calculate(nums, 0, 0, S);
return count;
}
public void calculate(int[] nums, int i, int sum, int S) {
if (i == nums.length) {
if (sum == S) {
count++;
}
} else {
calculate(nums, i + 1, sum + nums[i], S);
calculate(nums, i + 1, sum - nums[i], S);
}
}
}
class Solution {
public:
int count;
void backtrack(vector<int>& nums, int target, int start, int sum){
if(start==nums.size()){
if(sum==target){
count++;
}
return;
}
else{
for(int i=start; i<nums.size(); i++){
//sum+=nums[i];
backtrack(nums, target, i+1, sum+nums[i]);
sum-=nums[i];
}
}
}
int findTargetSumWays(vector<int>& nums, int target) {
count=0;
int sum=0;
int total=0;
for(auto x:nums)total+=x;
vector<vector<int>> dp;
backtrack(nums, target, 0, sum);
return count;
}
};

While/if Loop is not working in class

I'm learning java and I'm having an issue with my if code not running.
In the following code I'm trying to determine if a number (variable num) is a triangle number (1,3, 6, 10 etc). The code should run through and give the "Is Triangle". However it keeps spitting out Null.
I understand this is not the most effective way to do this code, but I am trying to learn how to use Classes.
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 45;
int tri = 0;
int triplus = 0;
String triresult;
public String triangle() {
while (tri < num) {
if (tri == num) {
triresult = "Is a Triangle";
System.out.println("Is a Triangle");
} else if (tri + (triplus + 1) > num){
triresult = "Is Not a Triangle";
} else {
triplus++;
tri = tri + triplus;
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Thanks for any help provided.
Try this code :
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 10;//Try other numbers
int tri = 0;
int triplus = 0;
int res = 0;
String triresult = "Is Not a Triangle";
int[] tab= new int[num];
public String triangle() {
//to calculate the triangle numbers
for(int i = 0; i<num; i++){
res = res + i;
tab[i]=res;
}
//To check if num is a triangle or not
for(int i = 0; i<tab.length; i++){
System.out.println(">> " + i + " : " + tab[i]);
if(tab[i]== num){
triresult = num + " Is a Triangle";
break;//Quit if the condition is checked
}else{
triresult = num + " Is Not a Triangle";
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Hope this Helps.
Step through the loop carefully. You'll probably see that there is a case where
(tri < num)
fails, and thus you fall out of the loop, while
(tri == num)
and
(tri + (triplus + 1) > num)
both fail too, so no text gets set before you fall out.
You probably want to do your if-tests within the method on just tri, not a modification of tri, so as to reduce your own confusion about how the code is working.

passing method name as parameter for threadpool queuserworkitem

QueUserWorkItem is supposed to accept a delegate but i found exercise that passes instance method name instead of delegate like this:
public class Fibonacci
{
private int _n;
private int _fibOfN;
private ManualResetEvent _doneEvent;
public int N { get { return _n; } }
public int FibOfN { get { return _fibOfN; } }
// Constructor.
public Fibonacci(int n, ManualResetEvent doneEvent)
{
_n = n;
_doneEvent = doneEvent;
}
// Wrapper method for use with thread pool.
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("thread {0} started...with id={1}", threadIndex,Thread.CurrentThread.ManagedThreadId);
_fibOfN = Calculate(_n);
Console.WriteLine("thread {0} result calculated...", threadIndex);
_doneEvent.Set();
}
// Recursive method that calculates the Nth Fibonacci number.
public int Calculate(int n)
{
if (n <= 1)
{
return n;
}
return Calculate(n - 1) + Calculate(n - 2);
}
}
public class Program
{
static void Main()
{
const int FibonacciCalculations = 10;
// One event is used for each Fibonacci object.
ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
Random r = new Random();
// Configure and start threads using ThreadPool.
Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
for (int i = 0; i < FibonacciCalculations; i++)
{
doneEvents[i] = new ManualResetEvent(false);
Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);
fibArray[i] = f;
ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback , i);
}
for (int x = 0; x < 10;x++ )
{
Console.WriteLine("x");
}
// Wait for all threads in pool to calculate.
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("All calculations are complete.");
// Display the results.
for (int i = 0; i < FibonacciCalculations; i++)
{
Fibonacci f = fibArray[i];
Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
}
}
}
why does this work? I do not see implicit or explicit delegate being passed

Fibonacci Sequence error

I am coding a Fibonacci sequence in Eclipse and this is my code-
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
It is showing an error in the return value; line saying value cannot be resolved to a variable. I don't see any other errors.
Where is value defined? You return something that was not defined anywhere.
You don't have a "value" defined, this is your error. I don't remember the thing exactly, but I think you don't need a and b, I found this in my code archive, hope it helps.
public class Fibonacci
{
public static long fibo(int n)
{
if (n <= 1) return n;
else return fibo(n - 1) + fibo(n - 2);
}
public static void main() {
int count = 5; // change accordingly, bind to input etc.
int N = Integer.parseInt(count);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fibo(i));
}
}
In case you want to stay with your own code, try returning "b" as value.
Your method is returning an int variable so you would have to define and return value as an int
I am not sure what you trying to do.
If you have "getValue" method I think "increment" method should be void.
When you want current Fibonacci value use "getValue" method.
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public void increment() {
int temp = b;
b = a + b;
a = temp;
}
public int getValue() {
return b;
}

Does one need getters and setters for calculation methods?

import javax.swing.JOptionPane;
public class BeerStoreBP
{
private String name;
private double custAge;
private double numBeers = 0;
private double beerDisc = 0;
private double beerType = 0;
private double theBeerBrand;
private double total = 0;
private double beer = 0;
public void setAge(double theAge)
{
custAge = theAge;
}
public void setName(String theName)
{
name = theName;
}
public void setNumBeers(double theNumBeers)
{
numBeers = theNumBeers;
}
public void setBeerType(double theBeerType)
{
beerType = theBeerType;
}
public double getAge()
{
return custAge;
}
public String getName()
{
return name;
}
public double getNumBeers()
{
return numBeers;
}
public double calcNumBeersValid()
{
String numBeersStr;
while (numBeers < 3 || numBeers > 6)
{
numBeersStr = JOptionPane.showInputDialog("You must pick 3-6 " +
"beers");
numBeers = Double.parseDouble(numBeersStr);
}
return numBeers;
}
public double calcBeerPrice()
{
final double LAGIMRED = 1.90;
final double DESINIPA = 2.00;
final double BELBEBRN = 1.80;
final double SCHOATST = 2.50;
final double BOULFHSAISN = 2.75;
final double GANDANCPRTR = 1.75;
if (theBeerBrand == 1)
beer = LAGIMRED;
else if (theBeerBrand == 2)
beer = DESINIPA;
else if (theBeerBrand == 3)
beer = BELBEBRN;
else if (theBeerBrand == 4)
beer = SCHOATST;
else if (theBeerBrand == 5)
beer = BOULFHSAISN;
else
beer = GANDANCPRTR;
return beer;
public double calcBeerTotal()
{
String beerTypeStr;
double count = 1;
while (count <= numBeers)
{
beerTypeStr = JOptionPane.showInputDialog("Please choose between "
+ "these fine selections:\n1 - Lagunitas Imperial Red - " +
"$1.90\n2 - Deschutes Inversion IPA - $2.00\n3 - " +
"Bell's Best Brown Ale - $1.80\n4 - Schlafly's Oatmeal " +
"Stout - $2.50\n5 - Boulevard's Farmhouse Saison - $2.75"
+ "\n6 - Gandy Dancer Porter - $1.75");
beerType = Double.parseDouble(beerTypeStr);
beerType = theBeerBrand;
total += beer;
count++;
}
return total;
}
public double getBeerTotal()
{
double theTotal;
theTotal = total;
return theTotal;
}
public double calcBeerDisc()
{
if (numBeers == 6)
beerDisc = .10;
else if (numBeers >= 4)
beerDisc = .05;
else
beerDisc = .00;
return beerDisc;
}
public double calcFinalPrice()
{
double finalPrice;
finalPrice = total-(total * beerDisc);
return finalPrice;
}
Noob here, so please shed some mercy. The point of the above program is to gather the amount of beers(must be 3-6), provide the customer with a choice for each beer, calculate the total amount of beers, and apply a discount(depends on # of beers). Pretty simple stuff, yet I've hit a brick wall.
My problem lies with calculating the final price. I can't seem to figure out why nothing from by calcBeerTotal method is getting passed to my calcFinalPrice method. My output displays the amount of beers just not the final price.
So my main question is: do I need some sort of setter and getter method for my calc methods? I've tried some setter and getter methods and I still wasn't getting a final price (method located above calcBeerDisc). I'm of limited programming knowledge so please keep from getting any more complicated than what I've written. If it's something aside from setters and getters please keep away from arrays and the like as I do not fully understand them either. Any help is much appreciated!
Rewritten:
import javax.swing.JOptionPane;
public class BeerStoreBP {
private String name;
private double custAge;
private double numBeers = 0;
private double beerDisc = 0;
private double total = 0;
// This only exists in one method. There is no need for it to be global
//private double beerType = 0;
// This only exists in one method. There is no need for it to be global
//private double theBeerBrand;
// This only exists in one method. There is no need for it to be global
//private double total = 0;
// This only exists in one method. There is no need for it to be global
//private double beer = 0;
public void setAge(double theAge)
{
custAge = theAge;
}
public void setName(String theName)
{
name = theName;
}
public void setNumBeers(double theNumBeers)
{
numBeers = theNumBeers;
}
// Your functionality is parsed by your dialog. There is no need for this.
//public void setBeerType(double theBeerType)
//{
// beerType = theBeerType;
//}
public double getAge()
{
return custAge;
}
public String getName()
{
return name;
}
public double getNumBeers()
{
return numBeers;
}
public double calcNumBeersValid()
{
String numBeersStr;
while (numBeers < 3 || numBeers > 6)
{
numBeersStr = JOptionPane.showInputDialog("You must pick 3-6 " +
"beers");
numBeers = Double.parseDouble(numBeersStr);
}
return numBeers;
}
public double calcBeerPrice(int beerBrand)
{
final double LAGIMRED = 1.90;
final double DESINIPA = 2.00;
final double BELBEBRN = 1.80;
final double SCHOATST = 2.50;
final double BOULFHSAISN = 2.75;
final double GANDANCPRTR = 1.75;
double beerPrice;
if (beerBrand == 1)
beerPrice = LAGIMRED;
else if (beerBrand == 2)
beerPrice = DESINIPA;
else if (beerBrand == 3)
beerPrice = BELBEBRN;
else if (beerBrand == 4)
beerPrice = SCHOATST;
else if (beerBrand == 5)
beerPrice = BOULFHSAISN;
else
beerPrice = GANDANCPRTR;
return beerPrice;
}
public void calcBeerTotal()
{
String beerTypeStr;
double count = 1;
double beerPrice;
// No need to be double
int beerBrand;
while (count <= numBeers)
{
beerTypeStr = JOptionPane.showInputDialog("Please choose between "
+ "these fine selections:\n1 - Lagunitas Imperial Red - " +
"$1.90\n2 - Deschutes Inversion IPA - $2.00\n3 - " +
"Bell's Best Brown Ale - $1.80\n4 - Schlafly's Oatmeal " +
"Stout - $2.50\n5 - Boulevard's Farmhouse Saison - $2.75"
+ "\n6 - Gandy Dancer Porter - $1.75");
beerBrand = Integer.parseInt(beerTypeStr);
beerPrice = calcBeerPrice(beerBrand);
total += beerPrice;
count++;
}
}
public double getBeerTotal()
{
return total;
}
public double calcBeerDisc()
{
if (numBeers == 6)
beerDisc = .10;
else if (numBeers >= 4)
beerDisc = .05;
else
beerDisc = .00;
return beerDisc;
}
public double calcFinalPrice()
{
double finalPrice;
finalPrice = total-(total * beerDisc);
return finalPrice;
}
}
This is in a working state, but may I recommend you take the UI portions out of this class and include them elsewhere.