I must be failing to wrap my head around the concept of trying to store a value in a recursive method. Solving this using iteration would take seconds, but I am struggling with the recursive call. Basically I am trying to solve: 1/1 + 1/2 + 1/3 ...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter in the end number for the sequence: ");
int endpoint = input.nextInt();
System.out.println("The value of the sequence is : " + calcSequence(endpoint));
}
public static double calcSequence (int index){
if (index == 0)
return 0;
else
return (1/index) + calcSequence(index - 1);
}
You need to add some explicit type conversions. Your 1/index is being performed as integer division, and your call is losing all its precision. Simply changing this to 1.0/index (or 1d/index to indicate that the 1 should be used as a double) should get you what you're looking for.
Related
this is such a simple problem but for some reason, I cant wrap my head around Array of Objects or Object Arrays. All I have to do is take in 5 user inputs, and create a class called Height, create object array and store user inputs into obj array and print the average. I'm kinda stuck.
class Height{
int total=0;
int count=0;
public Height(int y) {
total=total+y;
count++;
}
public void print() {
System.out.print("The average is: "+total/count);
}
}
public class ObjectArray {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter 5 heights in inches: ");
int[] x=new int[5];
int total=0;
for(int i=0;i<x.length;i++) {
x[i]=s.nextInt();
}
Height[] h=new Height[x.length];
for(int y=0;y<x.length;y++) {
h[y]=new Height(x[y]);
}
h.print();
}
}
Maybe I'm over complicating it. The problem right now is that I cannot invoke h.print();. I've tried different iterations, ex: taking out the print method and doing all the printing after every iteration.
Your approach is wrong. Your Height class appears to be responsible for the evaluation of the mean value. Hence, you should put all values inside a single Height instance, instead of generating a new instance for each user value.
However, h is an array of Heights object, while print() method is defined on a single Height instance. In order to call such method, you have to access one of the objects contained in h, that is h[0].print().
I'm assuming that your goal is simply to print the average of all the heights recieved via user input.
Your code in your main method is a tad confusing, so correct me if I'm wrong in any of the examples I give here. You should, instead of creating the x[] array, simply add the user input for the five values to Height.total in a for loop, and increase the Height.count variable by one each loop through. This should look something like this:
for (int i = 1; i <= 5; i++) {
// System.out.println("Please enter the next height: ");
Height.total += s.nextDouble();
Height.count++;
}
Then, you can run Height.print();.
I would also recommend adding a System.out.print(""); command to let the user know that they should enter the next value. That's the comment I left in the example code I gave above.
You have to design your Height in a way that match your requirement :
you need different Height with for each one a value
you need to know how many instances there is
For that, you need a private value, and a static counter :
class Height {
private int value = 0;
private static int count = 0; // static => nb of instances
public Height(int y) {
value = y;
count++;
}
public static int averageOf(Height... heights) {
return Arrays.stream(heights).mapToInt(h -> h.value).sum() / count;
}
}
To get the average, because it doesn't depend on a particular instance, you can have a static method, that sums all the value of the Height given and divide by the nb of instance
And use like :
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int nb = 5;
System.out.println("Enter " + nb + " heights in inches: ");
Height[] heights = new Height[nb];
for (int i = 0; i < heights.length; i++) {
heights[i] = new Height(Integer.parseInt(s.nextLine()));
}
System.out.println("Average is " + Height.averageOf(heights));
}
Ok, I'm a beginner in java, learning on my own through websites and books. I tried a simple square root calculator with a for loop and a while loop (I've included what I tried below). Sadly, all my code does when I enter a number is terminate. Any help would be appreciated!
import java.util.Scanner;
public class The2RootProdject {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double rootIt = input.nextDouble();
double dummy = 0.0000000;
while (dummy != dummy * dummy) {
dummy += 0.0000001;
if (rootIt == dummy * dummy) {
System.out.println("the squar root of " + rootIt + " is "
+ (dummy * dummy));
}
}
}
}
You have a couple of problems here:
1) Logical bug: 0 == 0 * 0
<= This means while (dummy != dummy * dummy) {..} will never be untrue, and you'll never even enter the loop
2) Floating point numbers are inexact, so your algorithm (which relies on "==") might not work anyway
Look here for more details on floating point imprecision:
http://www.lahey.com/float.htm
This is true for ANY language - your algorithm for square root must take this into account.
Try to use this algorithm which use Newton's iteration:
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
double number, t, squareRoot;
Scanner input = new Scanner(System.in);
number = input.nextDouble();
squareRoot = number / 2;
do
{
t = squareRoot;
squareRoot = (t + (number / t)) / 2;
}
while ((t - squareRoot) != 0);
System.out.println(squareRoot);
}
}
Newton's iteration is an algorithm for computing the square root of a number via the recurrence equation:
X(n+1) = (X(n) + number/X(n))/2
I think the while condition is supposed to be =
while(rootIt != dummy * dummy) {}
Your current condition will only ever be true if you initialized dummy as 1; but I don't that would be what you want anyways.
I am getting this error that to me looks like I am not calling the method correctly. I have reviewed the past answers here but none have specifically addressed my problem as far as I can see. This is for a class project. I realize my math in the method is most likely not correct yet but I need to get the rest working then deal with an incorrect out put. Thanks a lot!
Here is my code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse);
}
public static int reverse(int num, int rNum) {
rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}
And My error Message:
PrintOutNumbersInReverse.java:28: error: cannot find symbol
System.out.println ("Your number in reverse is: " +reverse);
^ symbol: variable reverse location: class PrintOutNumbersInReverse 1 error
Change method implementation to:
public static int reverse (int num)
{
int rNum = 0;
...
return rNum;
}
and place, that is calling this method to:
System.out.println ("Your number in reverse is: " +reverse(num));
Then should be fine
When copy pasting this into eclipse, i noticed 2 things:
1.) your reverse() method doesn't return an int, but it should because the signature of the method says so: public static int reverse(int num, int rNum). Maybe return rNum, or whatever the logic behind it might be?
2.) second, you have not declared any reverse variable in the main method. Maybe you wanted a parameterized call of reverse()?
Also it looks like, you want in the reverse() method rNum to be an output parameter. In java you can't pass primitives by reference, so whatever you do with rNum inside the method, the changes will only be present in the scope of the method. So you might want to calculate something and actually return the results of your calculations.
You need to use reverse as a method, and not a variable. Also, you are passing in a variable that is not used: rNum. You see in reverse(int num, int rNum); right after you start, it sets your rNum to 0. So why pass a number in that will get set to zero?
I did this from my phone, but this should be working code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse(num)); //<-- notice how this is a method cause it has "()"
}
public static int reverse(int num) { //<-- this has "int num" in the "()". This is a parameter.
int rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}
//In the following lines of code the user is asked to enter a length to determine the volume of a regular icosahedron, however, when entered the programm always outputs 0.0 as the answer for the volume???
import java.io.*; //allows I/o statements
class VolumeIcosahedron //creating the 'volumeIcosahedron' class
{
//allows strings with exceptions to IO = input/output
public static void main (String[] args) throws IOException
{
BufferedReader myInput = new BufferedReader(
new InputStreamReader (System.in)); //system input/ output
String stringNum; // the number string
double V; // integer with decimals volume
int L; // integer required length
//System output
System.out.println("Hello, what is the required length");
stringNum = myInput.readLine();
L = Integer.parseInt(stringNum);
V = 5/12 *(3 + Math.sqrt(5))*(L*L*L);
System.out.println("The volume of the regular Icosahedron is " + V);
}
}
Because 5/12 in integer equals 0 so it always results in 0.
Try with 5.0 to force the division without involving integer division.
V = 5.0/12 *(3.0 + Math.sqrt(5))*(L*L*L);
I think this is the offending line:
V = 5/12 *(3 + Math.sqrt(5))*(L*L*L);
5/12 returns an int (whole number), which is always truncated down to 0, hence 0 * anything will return 0.
Change it to this, using the letter d to signify that these numbers are of type double:
V = 5d/12d *(3 + Math.sqrt(5))*(L*L*L);
The reason is that you are using integer inside the calculation.
With integer, you should see the division as an euclidean operation, ie a = bq + r.
So in your program, 5/12 will always return 0 (5 = 0 * 12 + 5).
If you change the line to be like this (replacing every integer by double):
V = 5.D/12.D *(3.D + Math.sqrt(5.D))*(L*L*L);
Then the result will be different.
public class BitStringOperations3
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
int setA = 0;
int setB = 0;
int elementsSetA = 0;
int elementsSetB = 0;
System.out.println ("How many integers are in set A?");
elementsSetA = in.nextInt ();
while (elementsSetA > 9 || elementsSetA < 0)
{
System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
elementsSetA = in.nextInt();
}
System.out.println ("How many integers are in set B?");
elementsSetB = in.nextInt ();
while (elementsSetB > 9 || elementsSetB < 0)
{
System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
elementsSetB = in.nextInt();
}
for (int i = 1; i <= elementsSetA; i++)
{
System.out.println ("Please enter integer number " + i + " in set A: ");
setA = add(setA, in.nextInt() );
}
for (int i = 1; i <= elementsSetB; i++)
{
System.out.println ("Please enter integer number " + i + " in set B: ");
setB = add(setB, in.nextInt () );
}
}
public static boolean setContainsValue (int set, int value)
{
boolean setContainsValue = (set & maskForValue) != 0;
return true;
}
public static int addValueToSet (int set, int newValue)
{
set = set | maskForValue;
return set;
}
public static void printSet (int set, int value)
{
int mask = 1;
System.out.print ("{");
for (int i = 0; i<= 9; i++)
{
if(( mask & set ) == 1)
System.out.print(i + " " );
int maskForValue = 1 << value;
set >>= 1; //set = (set >> 1);
}
System.out.println ("} ");
}
}
I am having trouble with an assignment for school. We are given the universal set U = {0-9}. I have to gather user input for both sets, and then use bit strings (we are not allowed to use the Set or HashSet classes in java) to store the sets and perform operations on them, such as complement, Set A union Set B and such. I know how to do those, but my code does not convert Sets A and B into the memory correctly and therefore, I cannot perform any operations on them. Help will be gladly appreciated! Thanks in advance. :)
Edit 1:
Alright, I read your ideas and tried to implement them as good as I could, and I have given the result above. This program really pushes me out of my comfort zone and I really appreciate all the help.
First of all, do yourself a favour and create helper methods. Then concentrate only on making them correct:
public static boolean contains(int set, int value) {
//return true if value bit is 1 in set
}
public static int add(int set, int newValue) {
//add newValue to set and return it
}
Afterwards you can express your logic more clearly:
if ( contains(set, 1) ) {
//print 1
}
Some general hints:
Don't use Math.pow() as that is made for floating-point numbers. To get a power of 2 as an integer, use bit shifting:
int maskForValue = 1 << value;
To check if a certain bit is set, find the mask for that bit and use &. This zeros out all bits except for the bit you're checking.
boolean setContainsValue = (set & maskForValue) != 0;
To set a bit in a bit field, find the mask for that bit and use |. This ensures that that bit becomes 1.
set = set | maskForValue;
Edit
As to your direct problem, take a look at this:
for (int i = 1; i <= elementsSetB; i++)
{
System.out.println ("Please enter integer number " + i + " in set B: ");
setB = in.nextInt ();
}
You're overwriting setA and setB every time. In the end, setA and setB will contain the last value the user specified. Then later, you do this:
for (int i = 0; i <=9; i++)
setB |= (int)pow(2.0, i-1);
Which just ignores the user's input and overwrites all bits 0-9 (though in an unsafe way!). So of course what the user inputs is irrelevant.
Get rid of the latter for loops and then store the input like this (using the helper methods I described above):
for (int i = 1; i <= elementsSetB; i++)
{
System.out.println ("Please enter integer number " + i + " in set B: ");
setB = add(setB, in.nextInt());
}
Edit 2
You seem to be having problems understanding where I'm coming from with my idea of these "helper" methods. If this is the first time you've worked with methods that have parameters, sorry for clouding up the issue. But they allow you to focus on getting one piece of functionality working at a time. I'll expand on what I mean more here:
public static boolean setContainsValue(int set, int value) {
//return true if the bit string (or bit set) represented by the "set" parameter
//contains the value stored in the "value" parameter
//see the FIRST and SECOND bullet points above for how to do this
}
public static int addValueToSet(int originalSet, int valueToAdd) {
//add the value stored in the "valueToAdd" parameter to the set represented by the
//"originalSet" parameter and return the result
//see the FIRST and THIRD bullet points above for how to do this.
}
I'll even write some tests for you too. The methods above haven't been implemented properly until at least all of the following print true:
int set = 0;
System.out.println( ! contains(set, 1) ); //make sure set doesn't contain 1
set = addValueToSet(set, 1);
System.out.println( contains(set, 1) ); //make sure set now contains 1
System.out.println( !contains(set, 2) ); //make sure set doesn't contain 2
set = addValueToSet(set, 2);
System.out.println( contains(set, 1) ); //make sure set still contains 1
System.out.println( contains(set, 2) ); //make sure set now contains 2
First, you need a class (this is object-oriented programming, right?) to contain the "DigitSet".
public DigitSet {
private BitSet digits;
public DigitSet() {
// digits contains one bit for each digit
digits = new BitSet(10);
}
... rest of DigitSet code goes here, like ...
/**
* Check if this set contains a particular digit.
*/
public boolean contains(int value) {
// check to see if value is a valid input (0-9)
// look in digits to see if the "right" bit is set.
}
public void set(int value) {
// check to see if value is a valid input (0-9)
// set the "right" bit in digits to 1.
}
public void clear(int value) {
// check to see if value is a valid input (0-9)
// set the "right" bit in digits to 0.
}
public DigitSet union(DigitSet other) {
// construct a "new" output DigitSet.
// Walk through all of the digits in "this" set
// if a digit is set in this set, set it in the output set.
// Walk through all of the digits in the "other" set
// if a digit is set in the other set, set it in the output set.
}
public String toString() {
// return a display string based on the set "digit" bits
}
}
Then the rest is just input handling and "perform the operation"
public static void main(String[] args) {
DigitSet first = new DigitSet();
// read in the values for the first digit set, for each value
// set the digit in first like so
first.set(value);
DigitSet second = new DigitSet();
// read in the values for the second digit set, for each value
second.set(value);
DigitSet result = first.union(second);
System.out.println("Result: " + result.toString());
}