Printing "*" with recursion [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I would need some help to solve one exercise. In this method I have to print the number of asterisks ("*") that are equal of 2 of power of x.
For example, if I have 2 of power of 2 it should print 4 asterisks ("****");
I have a method that returns me the right number, but I have problems using that number for printing those asterisks.
Here is my code:
public static int writeStars(int number) {
if (number == 0) {
return 1;
} else {
int number2 = 2 * writeStars(number - 1);
System.out.println(" number " + number2);
return number2;
}
}

Here's one idea for solving the problem, without giving away the solution in code.
Your thoughts are on the right track, realizing that 2x = 2 * 2x-1. To print 2x * characters, you can print 2x-1 twice. In your recursive method, have your base case print one * character, and have your recursive case make the recursive call twice, passing the appropriately adjusted value.

One way to do it is to create a string of 2^(i-1) stars at the i-th iteration. So, for 4 iterations (x=4), you will have 8,4,2,1 stars for each iteration. You can return the string of stars for each iteration and concatenate them to get the final string.
The terminating condition will be when the input size is 0. This code might help:
public static String writeStars(int y) {
//y is 2^x
if( y == 0)
return "";
int num_stars = y - y/2;
StringBuffer stars_Buffer = new StringBuffer(num_stars);
for (int i = 0; i < num_stars; i++){
stars_Buffer.append("");
}
return stars_Buffer.toString() + writeStars(y/2);
}
Call writeStars with input 2^x:
writeStars(Math.pow(2, x));

Because it is a return method in your client you should have
int num = writeStars(someNum);
Then to print, you just need a simple for loop
for(int i=0; i < num; i++)
System.out.print("*");

Related

Absolutely dead confused about what is going in this code and problem. Can someone explain to me where to even begin? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I have to apply linear scan to this problem, and I just don't even know where to start. I feel as if I should change my career path honestly, this is a simple intro problem and i'm just not understanding anything about it.
/**
* Applies the linear scan strategy to counting the number of negative
* values in an array.
*/
public class CountNegatives {
/**
* Returns the number of negative values in the given array.
*/
public static int countNegatives(int[]a) {
neg=0;
for{i=0;i<a.length;i++}
if(i>0)
neg = neg+1;
return neg;
}
}
I've tried running this in VS and a tool my school uses called JGrasp. Both told me the { should be ( , the ; between length and i should be > , i<a.length is not a statement, and that } should be ;
When I change any of these things, it tells me variable neg=0 cannot be found and doubles the amount of errors in the code.
There are a few things you missed,
You did not initialize the neg=0; value with the proper data type; you should initialize it with the proper data type, which int his case is int, correct initialization would be int neg = 0;
the other problem would be in the for loop you still need to initialize i with a data type
the if statement is wrong, it should be 'i<0' instead cause with your code you are just counting the positive values
You are comparing the index value with 0 so you won't get the right value, instead, you should compare the value in the array that corresponds to that index, you can do this by arrayName[index].
The correct code would be as follows:
static int countNegatives(int[] a) {
int neg = 0;
for(int i = 0; i < a.length; i++) {
if(a[i] < 0) neg++;
// this will just work as neg = neg +1;
}
return neg;
}
}
public class CountNegatives {
/**
* Returns the number of negative values in the given array.
*/
public static int countNegatives(int[]a) {
int neg=0;
for(int number : a){
if(number<0) {
neg=neg+1;
}
}
return neg;
}
}

If else loop not adding valuing to variable using +=? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have a 1D matrix with data and another with scores. I'm trying to loop across all of the elements in the data and find the element in the same position in the score matrix, and keep adding these values together during each loop. For some reason, my script keeps starting from sum = zero instead of retaining and adding to the sum from the previous loop. For the below example, I expect sum = 1 in the first loop, 3 after the second loop (since 1+2=3) and 6 after the third loop (3+3=6). Instead, sum just yields the last value retrieved from scores. What am I doing wrong here?
public static int calc_score( )
{
String [] dat = {"A", "B","C"};
int [][] scores = new int [1][3];
scores[0][0] = 1;
scores[0][1] = 2;
scores[0][2] = 3;
int sum = 0;
for (int i = 0; i < dat[0].length(); i++)
{
if (dat[i].equals("A")) {
sum = sum + scores[i][0];
// scores[i][0] returns the expected value of 1 in the first loop
}
else if (dat[i].equals("B")) {
sum = sum + scores[i][1];
}
else if (dat[i].equals("C")) {
sum = sum + scores[i][2];
}
}
System.out.println(sum);
return sum;
}
I tried modifying sum = sum + scores[i][1]; to sum+=scores[i][1] but that doesn't fix this. I have to be missing something simple.
Learn to debug. Add println statements, or use a debugger, and track, on paper if you prefer, what you think the program should do. Where the computer does something different from what you thought: Voila. You found a bug; there may be more.
If you can't figure out why something is happening, go back and re-check assumptions.
Had you done that here, for example, you might have eventually noticed: Huh, that for loop really is only running exactly once, that's bizarre. Eventually you'd check what dat[0].length() returns and then realized it returns, mysteriously, 1, and perhaps then you'd have one of those slap yourself on the forehead moments: dat[0] refers to the first entry in the dat array, so, the string "A". Then you ask that string about length, which dutifully returns 1.
I assume you wanted dat.length instead.
Note that scores[1][0] is 0 too, you have more than one problem here.

Increasing value of variable in an if in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This is a basic question but I don't know why it isn't working.
I want that when a condition is satisfied, a variable increases its value in one (of course I've done this before but it isn't working). This is my code:
double count0 = 0;
if (neural.getResult(emg, eda, ax, ay, az, 1000) == 1){
count0 = count0 +1;
}
neural.getResult(emg, eda, ax, ay, az, 1000) is constantly reading real time values of sensors and it gives me 1 or 0 depending of those sensors, I'm trying to count how many ones it's giving me, but when I print count0 it only shows me a 1, like if it's only entering once in the if
If you want to have it executed more than once, you have to use a loop.
The general syntax for the while loop is:
while (condition)
{
//do sth..
}
So in your example this would get:
double count0 = 0;
boolean run = true;
while (run)
{
if (neural.getResult(emg, eda, ax, ay, az, 1000) == 1){
count0 = count0 + 1;
}
//add some sort of exit here.
if (your_stop_condition)
{
run = false;
}
}
But be careful: the above does execute infinitely, if you do not set run to false somewhere.
Is your case in a loop? If it is, then everytime you get into the case count0 will be 0 and add 1. So 0+1=1. When it enters the case again, count0 will be 0 once again and it will add 1 to 0(count0=0).
Put your count0 variable out of the loop if your case is in a loop

Does my program have a runtime error or does my computer not have the power to run my program? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I started the Euler Project and the first problem was very easy, however I cannot get the answer because the program I created is not running. It compiles fine but when I run it, it never runs. Project Euler says that the problems " with efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute." Which leads to my question. Am i stuck in an infinite loop or does my computer not have the power to run my program?
The problem is: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
public class Euler1
{
public static void main(String[] args)
{
double x = 1;
int count = 0;
int total = 0;
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
System.out.println(total);
}
}
Your program is wrong.
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
Notice that x is only incremented if the condition is true. x starts at 1, so the condition is not true, so x never gets incremented and stays at 1.
Also, x/3 == (int)x and x/5 == (int)x are not correct tests for divisibility. Neither of them are ever true unless x is 0.
The problem is that if your if condition is false in the while loop, x never gets incremented...
(and it will always be false unless x is 0)
You are getting stuck in an infinite loop. Your if-statement is never being called because it will never return true unless x is 0, and thus your x variable is never being incremented. I would suggest looking into the % (modulus) operator for this problem.

How to loop through an array to find the closest distance? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm stuck trying to figure out how to loop through an array of zip codes and find the closest zip code to a target. The zip codes also contain their latitude and longitude which is used to calculate the distance to the target. I need figure out how to loop through the array storing the closest distance and then returning the zip code of the closest one. Any help would be great because I've tried everything I can think of.
* Finds and returns the zip code of a postal zone in the collection
* whose centroid is closest to a given location.
*
* #param target the target location.
*
* #return returns zipCode of the postal zone whose centroid is closest;
* returns COLLECTION_EMPTY if no zones are in the collection.
*/
public String findClosestZone(Location target)
{
int counter = 0;
String closeZip = COLLECTION_EMPTY;
double closestDistance = 100.0;
for (int i = 0; i < this.zoneCount; i++)
{
if (this.zones[i].getZoneLocation()
.calcDistance(target) < closestDistance)
{
closeZip = this.zones[i].getZoneZipCode();
closestDistance = this.zones[i]
.getZoneLocation().calcDistance(target);
counter++;
return closeZip;
}
}
return closeZip;
}
According to doc:
A method returns to the code that invoked it when it
1. completes all the statements in the method,
2. reaches a return statement, or
3. throws an exception,
whichever occurs first.
It means that your code finishes its work after the first iteration. As far as I understand you want to find the closest one among array of zones.
I guess you don't need return inside loop. Please comment or delete it .
public String findClosestZone(Location target)
{
int counter = 0;
String closeZip = COLLECTION_EMPTY;
double closestDistance = 100.0;
for (int i = 0; i < this.zoneCount; i++)
{
if (this.zones[i].getZoneLocation().calcDistance(target) < closestDistance)
{
closeZip = this.zones[i].getZoneZipCode();
closestDistance = this.zones[i].getZoneLocation().calcDistance(target);
counter++;
// return closeZip;
}
}
return closeZip;
}

Categories