Why won't my for loop be used in the output? - java

These mailboxes were numbered 1 through 150, and beginning with mailbox 2, he opened the doors of all the even-numbered mailboxes, leaving the others closed. Next, beginning with mailbox 3, he went to every third mail box, opening its door if it were closed, and closing it if it were open. Then he repeated this procedure with every fourth mailbox, then every fifth mailbox, and so on.
I am trying to recreate this paragraph. I know my first and third function are find but for some reason my boolean is not using my loop in my second function in the output. Here is the code:
public class Lab {
public static void main (String[] args) {
Boolean[] mailboxarray = new Boolean[150];
closeMailboxes(mailboxarray);
doCrazyMailman(mailboxarray);
showMailboxstate(mailboxarray);
}
/**
* purpose:
* pre-condition:
* post-condition:
* #param mailboxarray
*/
public static void closeMailboxes(Boolean[] mailboxarray) {
for (int i = 0; i <150; i++) {
mailboxarray[i] = Boolean.FALSE;
}
}
/**
* purpose:
* pre-condition:
* post-condition:
* #param mailboxarray
*/
public static void doCrazyMailman(Boolean[] mailboxarray) {
// to help you with troubleshooting, I will add some outputs
// it is always beneficial to be able to see what's your program
// is actually doing right now
for (int i = 1; i <= 150; i++) {
for (int j = i; j < 150;j=j+i+1) {
}
}
}
/**
* purpose:
* pre-condition:
* post-condition:
*/
public static void showMailboxstate(Boolean[] mailboxarray) {
for (int i = 0; i < 150; i++) {
int number = i + 1;
// this will output only closed doors
// as shown in assignment's screenshot
// it reads next:
// if the current boolean is FALSE - display message
if (!mailboxarray[i])
System.out.println("Door " + number + " is closed");
}
}
}

Adapted your code to do the homework.
The catch is to look carefully at array indexes and know the use of negate boolean values.
class Lab {
public static void main(String[] args) {
Boolean[] mailboxarray = new Boolean[150];
closeMailboxes(mailboxarray);
doCrazyMailman(mailboxarray);
showMailboxstate(mailboxarray);
}
/**
* purpose: pre-condition: post-condition:
*
* #param mailboxarray
*/
public static void closeMailboxes(Boolean[] mailboxarray) {
for (int i = 0; i < 150; i++) {
mailboxarray[i] = Boolean.FALSE;
}
}
/**
* purpose: pre-condition: post-condition:
*
* #param mailboxarray
*/
public static void doCrazyMailman(Boolean[] mailboxarray) {
// to help you with troubleshooting, I will add some outputs
// it is always beneficial to be able to see what's your program
// is actually doing right now
for (int i = 2; i <= 150; i++) {
for (int j = i; j <= 150; j = i + j) {
// switch open-close by negate
// work with real case counter and take care to modify at proper place in arr
mailboxarray[j - 1] = !mailboxarray[j - 1];
// System.out.println(i + ":" + j + ":" + !mailboxarray[j - 1] + ":" +
// mailboxarray[j - 1]);
}
}
}
/**
* purpose: pre-condition: post-condition:
*/
public static void showMailboxstate(Boolean[] mailboxarray) {
for (int i = 0; i < 150; i++) {
int number = i + 1;
// this will output only closed doors
// as shown in assignment's screenshot
// it reads next:
// if the current boolean is FALSE - display message
if (!mailboxarray[i])
System.out.println("Door " + number + " is closed");
}
}
}
output
Door 1 is closed
Door 4 is closed
Door 9 is closed
Door 16 is closed
Door 25 is closed
Door 36 is closed
Door 49 is closed
Door 64 is closed
Door 81 is closed
Door 100 is closed
Door 121 is closed
Door 144 is closed

Related

How to print star pattern in java

I tried to find any sequence or formula for below star pattern but i did not found, so simply tried below
public class MyClass {
public static void main(String args[]) {
System.out.println("....*....");
System.out.println("...***...");
System.out.println("*********");
System.out.println(".*******.");
System.out.println("*********");
System.out.println("...***...");
System.out.println("....*....");
}
}
Here "." means " " space character.
Can we print this star using loop ?
Not sure what you mean, but if you really want a loop, here is a solution!
public class Star {
public static void main(String[] args) {
int[] dots = new int[] {4, 3, 0, 1, 0, 3, 4};
int width= 9;
for (int i = 0; i < dots.length; i++) {
for (int j = 0; j < width; j++) {
if (j < dots[i] || j > width - dots[i] - 1) {
System.out.print(".");
} else {
System.out.print("*");
}
}
System.out.println();
}
}
}
Hope It Helps! This is Easy to understand for Low Class Students Rather than Creating Arrays
class starPattern {
public static void main(String []args) {
for(int i=1;i<=7;i++) {
for(int j=1;j<=9;j++) {
if(i==3 || i==5 || j==5 || (i==4 && j>1 && j<9) || ((i==2 || i==6) && (j>3 && j<7))) {
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
My Computer Teacher Check it and it was Correct Method!
A Brief Description About this Pattern
1↓ 1→ 2 3 4 5 6 7 8 9
2 *
3 * * *
4 * * * * * * * * *
5 * * * * * * *
6 * * * * * * * * *
7 * * *
8 *
I'm using Java 11. You should be able to draw any enantiomorphic pattern of asterisks. Read the comments for detailed explanation.
import java.util.Arrays;
class Star {
public static void main(String[] args) {
int[] stars = new int[] { 1, 3, 9, 7, 9, 3, 1 }; // asterisks per line
int max = Arrays.stream(stars).max().getAsInt(); // max asterisks in any line
for (int i = 0; i < stars.length; i++) { // prints the asterisks for a given row, and pads it left and right with spaces
System.out.print(" ".repeat((max - stars[i]) / 2) + "*".repeat(stars[i]) + " ".repeat((max - stars[i] + 1) / 2));
}
}
Yes, it can be done using loops and should not be done via sout statements.
Also seems like you are a beginner in programming, so I will suggest you to try out logic for these kind of questions yourself. It will help in your growth.
Just try out line by line.
These questions generally need 2 loops, one to move in vertical direction and other to move in horizontal direction.
You can think it of as a i*j matrix( eg 3X3, 4X4).
So try it out yourself start with some basic one's.
If you still need solution just ping me but please try it on your own first.

Pyramid of pin using Recursion

I want to print a pyramid of pins using recursion(no Loops). I got the code almost done, but my pyramid is upside down, and it is not formatted. How can I fix it.
Below is my source code:
public void pinPattern(int count) {
if(count == 1)
System.out.println("*");
else {
System.out.print("*");
pinPattern(count - 1);
}
}
public int numberOfPins(int n) {
if(n == 0)
return 0;
else {
pinPattern(n);
return n + numberOfPins(n - 1);
}
}
public static void main(String[] args) {
Recursion x = new Recursion();
System.out.println("The number of pin: " + x.numberOfPins(5));
}
Thanks in advance.
So there are two considerations here. First, the need to have the pyramid go the other direction. If it is printing upside-down, then instead of counting down (which goes from max to min), invert the approach. Something like:
public static int pinPatternUp(int numPins, int maxPins)
{
if (numPins <= maxPins) {
// this will add spaces
spaces(maxPins - numPins);
pins(numPins);
return numPins + (pinPattern(numPins + 1, maxPins));
}
return 0;
}
The logic for the pins method (which in the OP's code was 'pinPattern) in the OP's approach is essentially fine for either direction. However, making this change (so that there is a space after each*`) will allow for a bit better formatting.
System.out.print("* ");
The second question is one of formatting. In this case, we can look at the pyramid as requiring N spaces before the first output. And with a bit of investigation, it appears that a given line will have the total number of rows - the current row in terms of spaces. Using recursion, it is possible to do something like:
public static void spaces(int num)
{
if (num == 0) {
return;
}
System.out.print(" ");
spaces(num - 1);
}
Note that one can now have an "up" or "down" facing pyramid depending upon whether the pinPattern is increasing or decreasing.
Note: due to some editing, the method names do not exactly align with the OP's.
public static void main(String[] args)
{
pinPatternUp(1, 5);
pinPatternDown(5, 5);
}
Output if run up and then down:
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*

numberOfDigits() in java? [duplicate]

This question already has answers here:
How to add a new method called numberOfDigits() in java?
(4 answers)
Closed 9 years ago.
i posted a question similar to this one but I still can't figure how to code this little part. Can someone please tell me how I can add a new method named "numberOfDigits"and a line to test it in the main() method . Below is the code I came up for numberOfZeros. To be more specific, all I want to know is how I can add numberOfDigits to this.
import java.util.*;
public class ZeroCounter {
public static void main(String[] args)
{
System.out.println("Enter a nonnegative number:");
Scanner keyboard = new Scanner(System.in);
int number = keyboard.nextInt( ) ;
System.out.println(number + " contains " + numberOfZeros(number) + " zeros.");
} // End of main
// * * * * Recursive Method * * * *
public static int numberOfZeros(int n) {
n = Math.abs(n); // Make sure the number is not negative.
// 1. STOPPING CONDITION: Number has only only digit.
if ( n < 10 ) {
// if( n == 0 ) return 1; else return 0;
return n==0 ? 1: 0 ; // Conditional operator.
} // end of the outer if block handling the stopping condition.
// 2. Else handle the case of two or more digits using recursion.
else {
return n%10 == 0 ? 1 + numberOfZeros(n/10): numberOfZeros(n/10) ; // Conditional operator.
// if (n%10 == 0) return 1 + numberOfZeros(n/10);
// else return numberOfZeros(n/10);
} // end of outer else block
} // end of recursive method method numberOfZeros. * * * * * * * *
// * * * * Non-recursive method using a while loop. * * * *
public static int numberOfZeros(int n)
{
if (n<0) n = -n;
if (n == 0) return 1; // Handle the special case of n = 0.
int zeros = 0; // The variable "zeros" will keep track of the number of zeros.
while (n > 0) { if(n%10==0) zeros++; n = n/10; }
return zeros;
} // End of NON_RECURSIVE method numberOfZeros.
// End of multiline comment below.
*/
} // end of class
int noOfDigits = (int) Math.log10(n) + 1;

Arraylist, do while loop and calling a method

I need to create an array list to save the value of resistors entered by user. Then I need to ask user which type of method to calculate his answer with, then return back answer. The do while loop needs to keep asking for resistors values until user enter the number zero. The calculations have to be pulled from a class Resistance to Main.
**CLASS***
import java.util.ArrayList;
public class Resistance {
/**
* Holds an object type.
*/
public int userChoice;
ArrayList<Double> resistor = new ArrayList<Double>();
/**
*Chooses which process follows next.
*#return circuitType
*/
public final double calculateResistance() {
if (userChoice == 1) {
return calculateSeriesResistance();
} else {
return calculaParallelResistance();
}
}
/**Returns object of parallel circuit.
*
* #return 1 / runningResistance.
*/
public double calculaParallelResistance() {
double runningResistance = 0;
for (int index = 0; index < resistor.lenght; ++index) {
runningResistance = runningResistance
+ +1 / resistor.lenght;
}
return 1 / runningResistance;
}
/**Returns object of series circuit.
*
* #return runningResistance.
*/
private double calculateSeriesResistance() {
double runningResistance = 0;
for (int index = 0; index < resistor.length; ++index) {
runningResistance = runningResistance + resistor[index];
}
return runningResistance;
}
}
***MAIN********
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
/**
* Makes a Constant.
*/
public final static int DONE = 0;
/**
* Makes a Constant.
*/
public static final int USER_CHOICE_SERIES = 1;
/**
* Makes a Constant.
*/
public static final int USER_CHOICE_PARALLEL = 2;
public static void main(final String[] args) {
// TODO Auto-generated method stub
DecimalFormat f = new DecimalFormat("##.00");
Resistance myRes = new Resistance();
Scanner keyboard = new Scanner(System.in);
//Display Purpose
System.out.println("\nThis program will calculate "
+ "the resistance of a Parallel or Series "
+ "Circuit\n");
//Display instructions
System.out.println("Please enter the value of your "
+ "resistors separately, when done press 0 (zero)");
int n = 0;
do {
System.out.println("Enter Resistor #" + ++n);
myRes.resistor.add(keyboard.nextDouble());
} while (myRes.resistor > 0);
// Ask Which Method To Use,
do {
System.out.println("\nEnter 1 to calculate "
+ "a Series Circuit "
+ "or 2 for a Parallel Circuit");
myRes.userChoice = keyboard.nextInt();
// Ask user again in case he enters something else
} while (myRes.userChoice != USER_CHOICE_PARALLEL
&& myRes.userChoice != USER_CHOICE_SERIES);
//Output the total resistance
System.out.printf("\nThe Total Resistance is "
+ f.format(myRes.calculateResistance()));
}
}
As said, there are few isues with your code, let's break it down step by step.
First, ArrayList doesn't have a field called length, you want to use size() instead.
Next, your method of calculating parallel resistance is wrong. You are not iterating over your resistors, instead you're using number of resistors to calculate. The correct formula is:
1 / Rtotal = 1 / R1 + 1 / R1 + 1 / R3 + ...
Change your code to:
public double calculaParallelResistance() {
double runningResistance = 0;
//use size() instead of length, which doesn't exist in ArrayList
for (int index = 0; index < resistor.size(); index++) {
//also, iterate over each resistor's value, and to get it,
//use...err, get() method :)
runningResistance += (1 / resistor.get(index));
}
return 1 / runningResistance;
}
Your method calculateSeriesResistance() also has an issue: you can't access object by using array notation, as in resistance[index]. Use get() method, so the correct code is:
private double calculateSeriesResistance() {
double runningResistance = 0;
for (int index = 0; index < resistor.size(); index++) {
runningResistance += resistor.get(index);
}
return runningResistance;
}
Now, to the main method. Your first 'do' loop is checking against number of resistors in your ArrayList, not against 0 value entered by user. You could use while loop instead and break when 0 entered:
//holds current resistor's value
Double val;
while(true) {
System.out.println("Enter Resistor #" + ++n);
val = keyboard.nextDouble();
//only add if higher than 0
if (val > 0.0) {
myRes.resistor.add(val);
}
//0 entered, so finish the loop
else break;
}

Project Euler p14, stackoverflowerror java (in bluej)

I'm working on euler problem 14 (http://projecteuler.net/problem=14). I've tried to tackle it by having a method which runs through the collatz equations, and returns the number of steps taken. If it's higher then the current record it overwrites it, otherwise it moves on to the next integer. It was giving stack overflow errors so I added the system.out.println messages to try and identify where it was stalling, and currently it dies whenever it reaches 5200~, I'm confused as to why, because as far as i can tell no values encountered at this point should go over the int limit, and the error persisted even if i changed "numberStorage" from int to long.
Here is my current code:
/**
* Write a description of class calculator here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Calculator
{
// instance variables - replace the example below with your own
private int x;
private int startingNumber = 1;
private int stepCount;
private int numberStorage;
private int currentRecordStart;
private int currentRecordSteps = 0;
/**
* a string and int value to track multiple starting numbers with the same number of steps
*/
private String tieNote = "no ties";
private int multiTie = 0;
/**
* Constructor for objects of class calculator
*/
public Calculator()
{
x = 0;
}
/**
* begins function
*/
public void initiater()
{
numberStorage = 0;
stepCount = 0;
startingNumber = 1;
currentRecordStart = 1;
currentRecordSteps = 0;
stepCount = 0;
recordHolder(1,1);
}
/**
* starts next rotation
*/
public void steprunner()
{
++startingNumber;
System.out.println("starting rotation " + startingNumber + " current record " + currentRecordSteps);
stepCount = 0;
numberStorage = 0;
recordHolder(startingNumber, collatzSequence(startingNumber));
}
/**
* Runs collatz sequence and updates a variable with the number of steps.
*/
public int collatzSequence(int N)
{
numberStorage = 0;
numberStorage = N;
if (N == 1)
{
return stepCount;
}
else if ( (N & 1) == 0)
{
numberStorage = numberStorage / 2;
++stepCount;
return collatzSequence(numberStorage);
}
else if ( (N & 1) != 0)
{
numberStorage = 3 * numberStorage + 1;
++stepCount;
numberStorage = numberStorage / 2;
++stepCount;
return collatzSequence(numberStorage);
}
return stepCount;
}
/**
* stores record and starts next cycle
*/
public void recordHolder(int startingnumber, int stepcount)
{
if (startingNumber <= 999999)
{
if (stepcount > currentRecordSteps)
{
currentRecordSteps = stepcount;
currentRecordStart = startingnumber;
tieNote = "no ties";
multiTie = 0;
System.out.println("a tie occured!");
}
else if (stepcount == currentRecordSteps)
{
tieNote = ("starting number " + startingnumber + " also had " + stepcount + "steps");
++multiTie;
System.out.println("a secondary tie occured!");
}
steprunner();
}
if (startingNumber == 999999)
{
simulationEnder();
}
}
/**
* ends simulation
*/
public void simulationEnder()
{
System.out.println("the number with the highest number of steps was " + currentRecordStart +
" with " + currentRecordSteps + " steps!");
}
}
I'm not going to read your code. But I can show you a solution, written in pseudocode, that is simple and quick:
function euler14(n):
cs := makeArray(1..n)
maxX, maxLen, cs[1] := 1, 1, 1
for k from 2 to n
c, s := 0, k
while k <= s
if s % 2 == 0
s := s / 2
else
s := 3 * s + 1
c := c + 1
cs[k] := cs[s] + c
if maxLen < xs[k]
maxX, maxLen := k, cs[k]
return maxX
The trick is to calculate and save the values of the lengths of the collatz chain, in order starting from 1; then, if a future sequence drops below its starting point, calculation stops in favor of a simple lookup. Here the cs array is the cache, k is the index of the chain that is currently being computed, s is the current item in the chain, and c is the current length of the chain. Computing euler14(1000000) should take no more than a second or two.

Categories