I need help with an exercise I am doing. I am currently learning Java. I am doing a factorial exercise, whereby my application prompt a user of a number and then compute the factorial of that number and returned it to be displayed.
This is my GUI class:
public String factorial;
public String fieldnumber;
public String calculateFactorial() {
fieldnumber = this.numberField.getText();
Number number = new Number(Integer.parseInt(fieldnumber));
System.out.print(number.toString());
return number.toString();
}
private void calculateBtnActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println( this.calculateFactorial());
}
This is my Number class:
public class Number {
private int number;
int i,fact=1;
public Number(int number){
this.number = number;
}
public Integer getNumber(){
return this.number;
}
public void setNumber(int number){
this.number = number;
}
private Integer computeFactorial(){
for(i=1; i<=number ;i++){
fact=fact*i;
}
return this.fact;
}
public String toString() {
return Integer.toString(this.computeFactorial());
}
}
When I print my computed factorial the true result is part of the printed garbage value. factorial of 6 is 720, but I am seeing 720518400 the first three numbers are the correct and the garbage not sure where it's coming from.
Please, help
Before the for loop, you must initialize fact=1; because you call the method twice.
private Integer computeFactorial(){
fact = 1;
for(i=1; i<=number ;i++){
fact=fact*i;
}
return this.fact;
}
Related
So I'm super new to programming and java, a colleague sent me this challenge to build a simple calculator with all four operation (+, - , / , *) but for only too integers.
Now he's asked me to remove this limit of only two values.
(i.e. 10+20+10+12 = 52 )
how difficult is that, should I be learning this right now ?
public class Calculadora {
private int numero1;
private int numero2;
private int resultado;
public int soma(){
this.setResultado(numero1 + numero2);
return this.resultado;
}
public static int soma(final int numero1, final int numero2){
return numero1 + numero2;
}
public int subtrai(){
this.setResultado(numero1 - numero2);
return this.resultado;
}
public static int subtrai(final int numero1, final int numero2){
return numero1 - numero2;
}
public int multiplica(){
this.setResultado(numero1 * numero2);
return this.resultado;
}
public static int multiplica(final int numero1, final int numero2){
return numero1 * numero2;
}
public int divisao(){
this.setResultado(numero1 / numero2);
return this.resultado;
}
public static int divisao(final int numero1, final int numero2){
return (numero1 / numero2);
}
public int getNumero1() {
return numero1;
}
public void setNumero1(int numero1) {
this.numero1 = numero1;
}
public int getNumero2() {
return numero2;
}
public void setNumero2(int numero2) {
this.numero2 = numero2;
}
public int getResultado() {
return resultado;
}
private void setResultado(int resultado){
this.resultado = resultado;
} ```
Check out varargs:
public Integer sum(Integer... numbers) {
int sum = 0;
for (Integer number : numbers) {
sum += number;
}
return sum;
}
I would look in to the following topics:
infix, postfix, prefix, and the Stack class. That is the essence of evaluating and
processing mathematical expressions of arbitrary length.
If you just use + or - look into ArrayList ArrList... you can add all your operands with ArrList.add( input integer here) an use a for loop to add them: for (into i=0;i<ArrList.length();i++) { result +=ArrList[i];} If you use / and × you would have to sort your operands after the weight of your operators:2+3+4×2 , to use a loop you would have to record it to: (.4×2)+3+2
Note: If, for my first case, you got like 3-4 you would ad them ad Arr[0]=3 and Arr[1]=-3.
Program is to add and average and list amount of times the "addNumber" method is called.
I can make the Amount work, but nothing else
public class Main {
public static void main(String[] args) {
NumberStatistics stats = new NumberStatistics();
stats.addNumber(3);
stats.addNumber(5);
stats.addNumber(1);
stats.addNumber(2);
System.out.println("Amount: " + stats.amountOfNumbers());
System.out.println("sum: " + stats.sum());
System.out.println("average: " + stats.average());
}
public class NumberStatistics {
private int amountOfNumbers;
private int addNumber;
private double average;
private int sum;
public NumberStatistics() {
this.amountOfNumbers=amountOfNumbers;
this.average=0;
this.sum=0;
}
public void addNumber(int number) {
number=addNumber;
addNumber++;
// code here
}
public int amountOfNumbers() {
return addNumber;
// code , here
}
public int sum() {
return this.addNumber++;
}
public double average() {
return sum() / addNumber;
}
My incorrect output:
Amount: 4
sum: 4
average: 0.0
Ok lets start with the constructor.
public NumberStatistics() {
this.amountOfNumbers=amountOfNumbers;
this.average=0;
this.sum=0;}
Here when you create an object you initialize average and sum to 0 but
this.amountOfNumbers=amountOfNumbers; has no particular effect.
To sum up what i think you wanted to do is something like this:
public NumberStatistics()
{
this.average = 0;//this keyword here is not needed but i used it since you did too
this.sum = 0;
this.amountOfNumbers = 0;
}
Then we go to this block of code here:
public void addNumber(int number) {
number=addNumber;
addNumber++;
}
Ok, this line makes no sense since you are setting the parameter equal to the addNumber variable which is something that does not help you at all, what i think you wanted to do here is the following:
public void addNumber(int number) {
sum += number;//same as sum = sum + number;
amountOfNumbers++;//same as amountOfNumbers = amountOfNumbers +1;
}
Then you need a method that returns the average like this:
public double average() {
return average = sum / amountOfNumbers; //i use the average variable only because you did,
//the most efficient way here is just to return sum / amountOfNumbers
}
Finally, the last two methods that i think you were trying to create are these:
public int amountOfNumbers() {
return amountOfNumbers;
}
public int sum() {
return sum;
}
This is my first post ever so i hope that it helps.
In NumberStatistics, you only need the count and a sum. You add to the sum with addNumber (and increment the count). Something like,
public class NumberStatistics {
private int count = 0;
private int sum = 0;
public void addNumber(int number) {
this.sum += number;
count++;
}
public int getCount() {
return count;
}
public int sum() {
return sum;
}
public double average() {
return sum() / (double) getCount();
}
}
Hi I'm very new to Java and have this HW problem, we are asked to build Class LTile, a tile in the game of Scrabble.
The ID number of a tile should be assigned by a class/static data member, which keeps track of the number of LTile objects produced.
My ID output didn't not print from 1 to 26, instead, they are all assign 26.
I suspect my ID attribute must be wrong, but couldn't figure out the exactly error. Any help is greatly appreciated! Thanks!
package hw2;
public class LTile {
char letter;
private int value;
private static int ID=0;
public LTile(){
this.letter = '?';
this.value = 0;
LTile.ID++;
}
public LTile(char letter, int value){
this.letter=letter;
this.value=value;
LTile.ID++;
}
public char getLetter(){
return this.letter;
}
public int getValue(){
return this.value;
}
public int getID(){
return LTile.ID;
}
public boolean equals(Object obj){
if(this ==obj){
return true;}
else{
return false;
}
}
public String toString(){
return "["+ID+":" + letter+","+value+"]";
}
//**
//** main() for testing LTile
//**
public static void main(String[] args)
{
final String letters = "EAIONRTLSUDGBCMPFHVWYKJXQZ";
final int[] values = {1,1,1,1,1,1,1,1,1,1,2,2,3,3,3,3,4,4,4,4,4,5,8,8,10,10};
java.util.List<LTile> lst = new java.util.ArrayList<LTile>();
for (int i = 0; i < letters.length(); ++i)
lst.add(new LTile(letters.charAt(i), values[i]));
for (LTile tile : lst)
System.out.println(tile);
System.out.println();
// test for equals
boolean found = false;
for (int i = 0; i < lst.size()-1; ++i) {
for (int j = i+1; j < lst.size(); ++j) {
if (lst.get(i).equals(lst.get(j))) {
System.out.println("ERROR in equals() found for "
+ lst.get(i) + " and " + lst.get(j));
found = true;
}
}
}
if (!found)
System.out.println("No error in equals().");
}
}
My output is:
[26:E,1]
[26:A,1]
[26:I,1]
[26:O,1]
[26:N,1]
[26:R,1]
[26:T,1]
[26:L,1]
[26:S,1]
[26:U,1]
[26:D,2]
[26:G,2]
[26:B,3]
[26:C,3]
[26:M,3]
[26:P,3]
[26:F,4]
[26:H,4]
[26:V,4]
[26:W,4]
[26:Y,4]
[26:K,5]
[26:J,8]
[26:X,8]
[26:Q,10]
[26:Z,10]
No error in equals()
**The correct output should be:**
[1: E,1]
[2: A,1]
[3: I,1]
[4: O,1]
[5: N,1]
[6: R,1]
[7: T,1]
[8: L,1]
[9: S,1]
[10: U,1]
[11: D,2]
[12: G,2]
[13: B,3]
[14: C,3]
[15: M,3]
[16: P,3]
[17: F,4]
[18: H,4]
[19: V,4]
[20: W,4]
[21: Y,4]
[22: K,5]
[23: J,8]
[24: X,8]
[25: Q,10]
[26: Z,10]
No error in equals().
The ID number of a tile should be assigned by a class/static data member, which keeps track of the number of LTile objects produced.
This means that the id value should come from a static data member, not that it should be a static data member. So you need two fields: an instance id field to keep the object's id and a static CURRENT_ID field to keep track of how many objects you have created so far.
public class LTile {
char letter;
private int value;
private int id; // instance id
private static int CURRENT_ID = 0; // static counter from where the instance ids will be drawn
public LTile() {
// Call the other constructor to avoid unnecessary repetition
this('?', 0);
}
public LTile(char letter, int value) {
this.letter = letter;
this.value = value;
this.id = LTile.CURRENT_ID++;
}
// rest of the code
public int getID() {
return this.id;
}
public String toString() {
return "["+this.id+":" + this.letter+","+this.value+"]";
}
}
Note you also need to change getId() and toString() to use the instance id instead of the static counter.
I'm writing a program that simulates simple bank account activities and I was wondering how to do it so that if I create a new Account without any parameters, it receives random 7digit identification number that is shown as String. The way I do, I only receive java.util.Random#2a0364ef in output.
Looking forward to any help and additional comments on this question as it is the first one I've posted on this website.
import java.util.Random;
class Account {
String id;
double stan;
int num;
static int counter;
public Account() {
**id = randomId().toString();**
stan = 0;
num = ++counter;
}
public Account(String id) {
this.id = id;
stan = 0;
num = ++counter;
}
public Account(String id, double mon) {
stan = 0;
this.id = id;
this.stan = mon;
num = ++counter;
}
**static String randomId() {
Random rand = new Random(7);
return String.valueOf(rand);**
}
String getId() {
return id;
}
double getStan() {
return stan;
}
int getNum() {
return num;
}
#Override
public String toString() {
return "Account's id " + getId() + " and balance " + getStan();
}
}
public class Exc7 {
public static void main(String[] args) {
Account account = new Account("0000001"),
acount0 = new Account("0000002", 1000),
acount1 = new Account();
System.out.println(account + "\n" + account0 + "\n" + account1);
}
}
Change return String.valueOf(rand);
To
return String.valueOf(rand.nextInt());
Reason:
You are passing random Object to valueOf method, not the value you need. Call nextInt() method on it to get the desired random value.
Use this code:
Random rand = new Random(7);
return String.valueOf(Math.abs(rand.nextInt()));
Right now you are representing the Random instance.
Instead printing the String representation of the mathematical absolute of the next int of your random will do the trick.
The Math.abs part is important, otherwise you might have negative numbers.
Use
return String.valueOf(rand.nextInt());
otherwise you will get the string representation of the Random object and not of a random int that it can produce.
Can anyone see what is wrong with my code? I get 0 from return of the calculation.
Created a small calculation on second class and pass the result data to main class, then print.
main class
package javaapplication3;
public class JavaApplication3 {
public static void main(String[] args) {
cal bla = new cal();
bla.getRatio();
String dCount = String.valueOf(bla.getRatio());
System.out.print(dCount);
}
}
second class
package javaapplication3;
public class cal {
public int total = 11;
public int count = 2508;
public int calRatio;
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
public int getRatio () {
return (calRatio);
}
}
PS: By changing bla.getRatio to bla.caln(); worked. I think I've got other projects mixed up. Thanks for the input guys.
You're doing integer division, which truncates the result to an integer.
You need to cast either operand to double.
bla.getRatio();
String dCount = String.valueOf(bla.getRatio());
You never call the caln()-method, so calRatio is 0 forever.
Maybe you meant the following:
bla.caln();
String dCount = String.valueOf(bla.getRatio());
Plus, you try to divide integers. Try this:
public class cal {
public int total = 11;
public int count = 2508;
public double calRatio;
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
public double getRatio () {
return calRatio;
}
}
You never call the "setter" function caln(), so calRatio was never set. So it returns the 0 for calRatio.
replace
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
by this
public cal () {
calRatio = count / total;
System.out.print(calRatio);
}
Try this:
public static void main(String[] args) {
cal bla = new cal();
bla.caln();
String dCount = String.valueOf(bla.getRatio());
System.out.print(dCount);
}
I get 0 from return of the calculation.
As you should. 11 / 2508 does an integer division which is 0
If you want a non-zero I suggest changing
public double getAverage () {
return (double) total / count;
}
Normally you divide the total by the count to get the average.
It will return 0, always, because you are returning an int type. The result of your division will always be some floating point value, so you need to store it as such, and return it.
public class cal {
public int total = 11;
public int count = 2508;
public double calRatio;
public void caln() {
calRatio = (double)count / (double)total;
System.out.print(calRatio);
}
}