UPDATE: I've tried changing the return type on the getCalcMean() and calcMean() methods to double to make it more accurate, and everything inside the Person class works fine, but Inside the program class it's now saying "Incompatible Types: possible lossy conversion from double to int." at System.out.println(math1.calcMean(math1.getCalcMean())); I understand what the error means but I'm not sure how to fix it as the final result needs to be double and I thought java could calculate a double and int and get a double. What am I doing wrong?
<<>>
I'm trying to calculate the mean of the total after 999 is typed, but it keeps showing 0, and I can't see why.
Can someone tell me how to get my getCalcMean() method to show the mean as numTotal/count?
--- Class Program ---
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int num = 0;
int count = 1;
Math math1 = new Math(num, count);
while (num != 999) {
num = kb.nextInt();
if (num != 999) {
math1.adder(num);
count ++;
System.out.println("Total till now:" + math1.getNumTotal());
}
}
math1.setCount(count);
System.out.println(math1.getNumTotal());
System.out.println(math1.calcMean(math1.getCalcMean()));
//System.out.println(math1.getNum());
kb.close();
/*Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
Scanner scn = new Scanner(input);
int num = scn.nextInt();
Math math1 = new Math(num,0);
while(num != 999){
math1.adder(num);
input = kb.nextLine();
}
System.out.println(math1.getNumTotal());*/
} //main
}
---- Class Math ----
public class Math {
private int num;
private int numTotal;
private double mean;
private int count;
/*public Math(int num, int numTotal){
this.num = num;
}*/
public Math(int num, int count) {
this.num = num;
this.count = count;
}
//get//
public int getNum(){
return this.num;
}
public int getNumTotal(){
return this.numTotal;
}
public double getCalcMean(){
return this.mean;
}
//set//
public void setNumTotal(int value){
this.numTotal = value;
}
public void setNum(int value){
this.num = value;
}
public void setCalcMean(double value){
this.mean = value;
}
public void setCount(int value){
this.count = value;
}
//other
/*public void adder(int num){
numTotal = numTotal + num;
}*/
public void adder(int num) {
this.num = num;
numTotal = numTotal + this.num;
}
//added after//
public double calcMean(int num){
this.numTotal = numTotal;
mean = numTotal / this.count;
return mean;
}
}
counter ++ in your code is meaningless since you never pass it to Math object.
math1.getCalcMean() will return the mean in Math object but mean hasn't been calculated yet.
Advice:
Add getter and setter for counter in Math class.
Calculate the mean in getCalcMean() method.
Plese see the code below. I assume that you use 999 as the end flag so haven't took it into account. The counter is initialized with 0.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int num = 0;
int counter = 0;
Math math1 = new Math(num, counter);
while (num != 999) {
num = kb.nextInt();
if (num != 999) {
math1.adder(num);
counter ++;
math1.setCounter(counter);
System.out.println("Total till now:" + math1.getNumTotal());
}
}
System.out.println(math1.getNumTotal());
System.out.println(math1.getCalcMean());
//System.out.println(math1.getNum());
kb.close();
/*Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
Scanner scn = new Scanner(input);
int num = scn.nextInt();
Math math1 = new Math(num,0);
while(num != 999){
math1.adder(num);
input = kb.nextLine();
}
System.out.println(math1.getNumTotal());*/
} //main
}
And also the Math class.
public class Math {
private int num;
private int numTotal;
private int mean;
private int counter;
/*public Math(int num, int numTotal){
this.num = num;
}*/
public Math(int num, int counter) {
this.num = num;
this.counter = counter;
}
//get//
public int getNum(){
return this.num;
}
public int getNumTotal(){
return this.numTotal;
}
public int getCalcMean(){
mean = numTotal / this.counter;
return mean;
}
public int getCounter(){
return this.counter;
}
//set//
public void setNumTotal(int value){
this.numTotal = value;
}
public void setNum(int value){
this.num = value;
}
public void setCalcMean(int value){
this.mean = value;
}
public void setCounter(int counter){
this.counter = counter;
}
//other
/*public void adder(int num){
numTotal = numTotal + num;
}*/
public void adder(int num) {
this.num = num;
numTotal = numTotal + this.num;
}
//added after//
public void calcMean(int num){
mean = numTotal / this.counter;
}
}
Related
How can I test a class that returns the Fibonacci series?
I used an iterator for this code.
The FibonacciIteratorTest class is below.
public class FibonacciIterator implements Iterator<Integer>, Iterable<Integer>{
private int num1;
private int num2;
private int num3;
private int count;
private int to;
public FibonacciIterator(int to){
this.num1 = 0;
this.num2 = 1;
this.to = to;
this.count = -1;
}
public static Iterable<Integer> to(int num){
return new FibonacciIterator(num);
}
#Override
public Iterator<Integer> iterator(){
return this;
}
#Override
public boolean hasNext(){
if(count < to){
count++;
return true;
}
return false;
}
#Override
public Integer next(){
if(count < 2){
return count;
}
num3 = num1 + num2;
num1=num2;
num2=num3;
return num3;
}
}
Instead of 55, the expected values should be 0 1 1 2 3 5 8 13 21 34 55.
class FibonacciIteratorTest {
#Test
void shouldReturnFibonacciNumbers(){
FibonacciIterator fibonacciNumbers= new FibonacciIterator();
assertEquals(55,fibonacciNumbers.to());
}
}
Considering your fibonacciNumbers.to method returning int [] then you might want to use assertArrayEquals:
int arr[]={0,1,1,2,3,5,8,13,21,34};
assertArrayEquals(arr, fibonacciNumbers.to(10));
If your method fibonacciNumbers.to() returns other than int array, then please tell us, so that answer can be changed accordingly.
Assuming your FibonacciIterator.to(int) method returns an Iterator<Integer>:
#Test
void shouldReturnFibonacciNumbers(){
var groundTruth = new ArrayList(Arrays.asList(1,1,2,3,5,8,13,21,34,55)).iterator();
var fibonacciNumbers = new FibonacciIterator().to(10);
while(groundTruth.hasNext()){
if(!fibonacciNumbers.hasNext()){
fail("Length doesn't match");
}
assertEquals(groundTruth.next(), fibonacciNumbers.next());
}
}
I didn't test the code, but it should at least be close to working.
I tried to check the palindrome number and find the single digit sum of the palindrome numbers, but my code is not returning the proper value (I am finding it difficult to return the value of sum from the loops). Can anyone help me getting the mistake. Any help will be appriciated.
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
System.out.println(SumOfPalindromeNumber(inp));
}
private static int SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
sumpal+=inp[i];
if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
}
}
return sumpal;
}
private static int singledigitsum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singledigitsum(sum1);
}
return sum1;
}
}
Enter numbers
Check which numbers are palindromes.
If that number is a palindrome then find sum of its digits.
Code:
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
SumOfPalindrome sumOfPalindrome=new SumOfPalindrome();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
for(int i=0;i<n;i++)
{
if(sumOfPalindrome.isPallindrone(inp[i]))
{
System.out.println("No -> "+inp[i]+" Sum->"+sumOfPalindrome.sumOfDigits(inp[i]));
}
}
}//
public boolean isPallindrone(int no)
{
int r,sum=0,temp;
temp=no;
while(no>0){
r=no%10; //getting remainder
sum=(sum*10)+r;
no=no/10;
}
if(temp==sum)
{
return true;
}
else
{
return false;
}
}
public int sumOfDigits(int no)
{
int sum = 0;
while (no != 0)
{
sum = sum + no % 10;
no = no/10;
}
return sum;
}
}
I did not understand the purpose of sumpal in your code. You wanted a method which return sumOfPalindromes in an array. I commented the part which was wrong.
import java.util.Scanner;
public class SumOfPalindrome_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
//System.out.println(SumOfPalindromeNumber(inp));
SumOfPalindromeNumber(inp);
}
private static void SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
// sumpal+=inp[i];
/*if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
*/
System.out.println(singleDigitSum(inp[i]));
}
}
}
private static int singleDigitSum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singleDigitSum(sum1);
}
return sum1;
}
}
Apologies if this is not the case but this seems like you are looking for answers to a coding test.
Here's what I have so far from my code. this is an introductory course so we haven't covered more advanced topics yet. With what I gave so far I input number and press -1 but the program doesn't do anything.
WE HAVEN'T COVERED ARRAYS YET.
import java.util.Scanner;
public class DataSet {
private double value,count,sum, sumOfSquares, average;
public DataSet(double value)
{
this.value=value;
}
public double getAverage(){
int value=0;
int count=0;
double sum=0;
while(value != -1){
sum=sum+value;
average=sum/count;
}
return average;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a numbers to get average and standard deviation: ");
int value=input.nextInt();
DataSet s= new DataSet(value);
System.out.println(s.getAverage());
}
}
Try this below program. This class has only average method. You can add any number methods operating on values arraylist.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class DataSet {
private List<Integer> values;
public DataSet(List<Integer> values) {
this.values = values;
}
public double getAverage() {
int sum = 0;
double result = 0.0;
for (int value : values) {
sum = sum + value;
}
if (values.size() > 0) {
result = sum / values.size();
}
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> values = new ArrayList<Integer>();
System.out
.print("Enter a numbers to get average and standard deviation: ");
int value = input.nextInt();
while (value != -1) {
values.add(value);
value = input.nextInt();
}
DataSet s = new DataSet(values);
System.out.println(s.getAverage());
}
}
I made a program which asks the user for their pet name and assigns it states of mind for 5 rounds. If the pet gets too angry it is put down.
What I am having trouble with is allowing the user to restart to an earlier stage at the game before the pet died.
Compiling the code would help illustrate the issue.
Any help would be appreciated.
import java.util.Random;
import java.util.Scanner;
class dinoo {
public static void main(String[] p) {
Pet p1 = new Pet();
Pet p2 = new Pet();
Scanner scanner = new Scanner(System.in);
String petname;
String species;
String angerlevel;
int thirst;
int hunger;
int irritability;
explain();
petname = askpetname();
species = askpetspecies();
int howmanyrounds = 5;
for (int i = 0; i < howmanyrounds; i++) {
int number = i + 1;
String num = Integer.toString(number);
print("Round " + number);
String[] emotionalstate = newarray(5);
thirst = thirstlevel(p1);
hunger = hungerlevel(p1);
irritability = irritabilitylevel(p1);
angerlevel = anger(hunger, thirst, irritability);
p1 = setpetname(p1, petname);
p1 = setspecies(p1, species);
p1 = setthirst(p1, thirst);
p1 = setanger(p1, angerlevel);
p1 = sethunger(p1, hunger);
p1 = setangervalue(p1, irritability);
print(petname + "'s thirst level is " + thirst + " , hunger level is " + hunger + ", irritability level is " + irritability + " and therefore emotional state is " + angerlevel);
if (angerlevel.equals("DANGEROUS")) {
print(petname + " is looking " + angerlevel + ", get out now! we will have to put " + petname + " down.");
boolean continueEnd = petdead();
if (continueEnd == false) {
System.exit(0);
} else {
emotionalstate = wheretogo(emotionalstate[]);
}
} else if (angerlevel.equals("Serene")) {
print("He looks " + angerlevel + ". Seems in a good mood.");
} else if (angerlevel.equals("Grouchy")) {
print("You should give him a treat to cheer him up.");
}
whatdoyouwant(p1);
print("Your pets emotion is now " + anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1)));
emotionalstate[i] = anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1));
print("Emotional state " + emotionalstate[i] + " has been saved!");
}
System.exit(0);
}
public static String[] wheretogo(String[] a) {
Scanner scanner = new scanner;
print("which level would you like to return to?");
int number = scanner.nextInt();
String level = a[number];
return a;
}
public static boolean petdead() {
Scanner scanner = new Scanner(System.in);
print("Your pet has been killed. Would you like to continue? (True or False)");
boolean yesorno = scanner.nextBoolean();
return yesorno;
}
public static int inputint(String message) {
Scanner scanner = new Scanner(System.in);
System.out.println(message);
int answer = scanner.nextInt();
return answer;
}
public static String[] newarray(int arraylength) {
String[] emotionalstate = new String[arraylength];
return emotionalstate;
}
//takes input from user to cheerup/feed/sing to the animal to lower values stored in setter/getter
public static Pet whatdoyouwant(Pet p1) {
Scanner scanner = new Scanner(System.in);
print("what would you like to do to the pet? (treat/water/sing)");
String ans = scanner.nextLine();
Random ran = new Random();
int reduction = ran.nextInt(6);
if (ans.equalsIgnoreCase("treat")) {
int hunger = gethungervalue(p1) - reduction;
if (hunger < 0) {
hunger = 0;
}
p1 = sethunger(p1, hunger);
print("Your pets hunger has been reduced to:");
printint(gethungervalue(p1));
} else if (ans.equals("sing")) {
int irrit = getirritabilityvalue(p1) - reduction;
if (irrit < 0) {
irrit = 0;
}
p1 = setirritability(p1, irrit);
print("Your pets irritability hs been reduced to:");
printint(getirritabilityvalue(p1));
} else if (ans.equals("water")) {
int thirst = getthirst(p1) - reduction;
if (thirst < 0) {
thirst = 0;
}
p1 = setthirst(p1, thirst);
print("Your pets thirst is has been reduced to:");
printint(getthirst(p1));
} else {
print("That action seems to agitate your pet, try something else before your pet becomes dangerous!");
}
return p1;
}
//GETTER METHOD
public static String getpetname(Pet p) {
return p.name;
}
public static String getspecies(Pet p) {
return p.species;
}
public static String getanger(Pet p) {
return p.anger;
}
public static int getthirst(Pet p) {
return p.thirst;
}
public static int gethungervalue(Pet p) {
return p.hunger;
}
public static int getangervalue(Pet p) {
return p.angervalue;
}
public static int getirritabilityvalue(Pet p) {
return p.irritability;
}
//SETTER METHOD
public static Pet setangervalue(Pet p, int whatsangervalue) {
p.angervalue = whatsangervalue;
return p;
}
public static Pet setpetname(Pet p, String name) {
p.name = name;
return p;
}
public static Pet setspecies(Pet p, String petspecies) {
p.species = petspecies;
return p;
}
public static Pet setanger(Pet p, String howangry) {
p.anger = howangry;
return p;
}
public static Pet sethunger(Pet p, int howhungry) {
p.hunger = howhungry;
return p;
}
public static Pet setthirst(Pet p, int howthirsty) {
p.thirst = howthirsty;
return p;
}
public static Pet setirritability(Pet p, int howirritable) {
p.irritability = howirritable;
return p;
}
//Method printing out statement to explain functionality of program
public static void explain() {
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
//Method to ask the pet name
public static String askpetname() {
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
return petname;
}
//Method to ask the pet species
public static String askpetspecies() {
Scanner scanner = new Scanner(System.in);
print("What species is your pet?");
String petspecies = scanner.nextLine();
return petspecies;
}
//Randomly allocates thirst value 0-10
public static int thirstlevel(Pet p1) {
Random ran = new Random();
int thirst = ran.nextInt(11);
setthirst(p1, thirst);
return thirst;
}
//Randomly Allocates hunger value 0-10
public static int hungerlevel(Pet p1) {
Random ran = new Random();
int hunger = ran.nextInt(11);
sethunger(p1, hunger);
return hunger;
}
//randomly generates a irratibilty value
public static int irritabilitylevel(Pet p1) {
Random ran = new Random();
int irritable = ran.nextInt(11);
setirritability(p1, irritable);
return irritable;
}
//Method calculates the anger value based on the thirst/hunger/irritability average
public static String anger(int thirst, int hunger, int irritability) {
int angerscore = (thirst + hunger + irritability) / 3;
String temper;
temper = Integer.toString(angerscore);
if (angerscore <= 1) {
temper = "Serene";
} else if (angerscore <= 3) {
temper = "Grouchy";
} else if (5 < angerscore) {
temper = "DANGEROUS";
}
return temper;
}
//HELPER PRINT METHOD
public static String print(String message) {
System.out.println(message);
return message;
}
public static int printint(int message) {
System.out.println(message);
return message;
}
}//END class dinoo
class Pet {
String name;
String species;
int thirst;
int hunger;
String anger;
int irritability;
int angervalue;
} //END class pet
First of all you should look at the compile errors in your code before submitting a question here.
Please read the links provided in the comments to learn how to submit a proper question.
I tried to compile your code and it had the following errors:
java2.java:51: error: '.class' expected
emotionalstate = wheretogo(emotionalstate[]);
^
java2.java:75: error: '(' or '[' expected
Scanner scanner = new scanner;
That means in line 51, you're passing emotionalstate[] , which is emotional state array, whereas emotionalstate itself is an array, so you're passing an array of an array.
So just change it to emotionalstate = wheretogo(emotionalstate)
And in line 75, your initialization of Scanner object is wrong, change it to Scanner scanner = new Scanner();
I'm trying to add elements to an array. The elements of the array are of a custom class called variable. In the problematic for loop, it basically adds the last element trying to be added throughout the loop. Any help would be appreciated!
import java.util.*;
public class ThiefsDilemma2{
public static void main(String[] args){
ArrayList values = new ArrayList(args.length/2);
Valuable[] array = new Valuable[args.length/2];
if(args.length%2 ==1){
int weight = Integer.parseInt(args[args.length-1]);
boolean room = true;
int tracker = 0;
//problem!!!! Adds the last element throughout the loop
for(int i = 0; i < args.length/2; i++){
array[i] = new Valuable(
Integer.parseInt(args[args.length/2+i]),
Integer.parseInt(args[i]));
}
for(int i = 0; i < args.length/2; i++){
System.out.println(array[i]);
}
while(values.size() > 0 && room){
int lightest = 100000;
double value = 0.0;
int index = 0;
int counter = 0;
for(Object p: values){
Valuable test = (Valuable)p;
//System.out.println(test);
if(test.getWeight() < lightest && !test.beenUsed()){
lightest = test.getWeight();
//System.out.println(lightest);
}
if(test.getValue() > value && !test.beenUsed()){
index = counter;
value = test.getValue();
//System.out.println(value);
}
else if(test.getValue() == value || !test.beenUsed()){
if(test.getWeight() <= test.getWeight()){
index = counter;
}
}
counter++;
}
//System.out.println(counter + " " + lightest + " " + value);
Valuable p = ((Valuable)(values.get(index)));
p.used();
if(lightest > weight){ room = false;}
else{
if(p.getWeight() <= weight){
weight -= p.getWeight();
}
System.out.println(p);
values.remove(p);
}
}
}
}
public static class Valuable{
private static double value;
private static int weight;
private static boolean used = false;
public Valuable(int top, int bottum){
value = ((double)top/(double)bottum);
weight = bottum;
//System.out.println(weight + " " + value);
}
public static double getValue(){
return value;
}
public static int getWeight(){
return weight;
}
public String toString(){
return value + " " + weight;
}
public static void used(){
used = true;
}
public static boolean beenUsed(){
return used;
}
}
}
The problem is that all data members of Valuable are static. This means that they are shared by all instances of the class:
private static double value;
private static int weight;
private static boolean used = false;
Remove the static qualifiers from the data members, and from the getter functions.