Trouble with formatting output in loop - java

I have code that has multiple methods and we're suppose to call said methods to help us format an image made from characters. The image is a cake and uses characters like "=", "\", "^" and "/" among others I have yet to get too. Anyways using odd user input between 3 and 9 (3,5,7,9), we're suppose to format it so it prints out the other method and then the one before it. So If one method prints out "[|_______||_______||_______|]" and the other one prints out "[|___||_______||_______|____|]" with it's size varying with user input. If input is 3 it's suppose to print out both methods once as the hint was that it uses half the user input to decide how often to print something. The problem goes when I go beyond 3 to 5 or 7 as I get something like
/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\
[|_______||_______||_______||_______||_______|]
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
[|_______||_______||_______||_______||_______|]
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
\=============================================/
It's suppose to print one then the other, not two at once. Not only that but in total the methods are only suppose to print out 4 times if it's 5 so I'm suppose to get something like this instead. I think it's how I formatted my for loops for that method but I could be wrong, thank you in advance to anyone willing to help.
/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
\=============================================/
My "drawFullBrick" method prints out the [|_______||_______||_______||_______||_______|] part while the "drawHalfBrick" prints out the [|___||_______||_______||_______||_______|___|] part
public static void drawBrickStack (int sizeParam) {
System.out.print("/");
for (int count = 0; count < sizeParam * 9; count++)
System.out.print("^");
System.out.print("\\ \n");
for (int count = 0; count < sizeParam/2; count++)
{
for (int nestedCount = 0; nestedCount < sizeParam/2; nestedCount++)
{
drawFullBrickLine(sizeParam);
}
drawHalfBrickLine(sizeParam);
}

Related

How would you go about adding a space between every random number? [duplicate]

This question already has answers here:
Elegantly Insert Spaces During Loop Between Values Without Trailing Space
(3 answers)
Java: join array of primitives with separator
(9 answers)
Closed 6 months ago.
I'm trying to get the console to output 100 random numbers between 0 and 50, all on the same line with a space between each. I have everything but the formatting for the space. I know I need to use the printf function, but am completely lost on how to properly impliment it. This is what I have so far, but the output formatting is incorrect.
public static void main(String[] args) {
Random rand = new Random();
for (int count = 0; count <=100; count++)
{
int randomNum = rand.nextInt(51);
System.out.printf("%1d %1d", randomNum, randomNum);
}
}
Here's a version neither using a condition or a separate first print but avoiding any leading or trailing space.
public static void main(String[] args) {
Random rand = new Random();
String delim="";
for (int count = 0; count <100; count++)//fixed as per comments elsewhere.
{
int randomNum = rand.nextInt(51);
System.out.printf("%s%1d", delim,randomNum);
delim=" ";// Change this to delim="," to see the action!
}
}
It's a classic faff to print out n items with n-1 internal separators.
PS: printf feels like overkill on this. System.out.print(delim+randomNum); works just fine.
[1] Your code actually prints 101 numbers. Embrace the logic computers (and java) applies to loops and 'the fences' (the start and end): The first number is inclusive, the second is exclusive. By doing it that way, you just subtract the two to know how many items there are. so, for (int count = 0; count < 100; count++) - that loops 100 times. Using <= would loop 101 times.
[2] You're making this way too complicated by focusing on the notion of 'there must be a space in between 2', as if the 2 is important. What you really want is just 'after every random number, print a space'. The only downside is that this prints an extra space at the end, which probably doesn't matter:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum + " ");
}
is all you actually needed. No need to involve printf:
I know I need to use the printf function
No, you don't. No idea why you concluded this. It's overkill here.
If you don't want the extra space.. simply don't print it for the last number:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum);
if (count < 99) System.out.print(" ");
}
[3] You mention that the code shuold print it all 'on one line', which perhaps suggests the line also needs to actually be a line. Add, at the very end, after the loop, System.out.println() to also go to a newline before you end.

How to alter and display only one column (via user input) on 2D array Java

I am creating a game board. I need it to reveal a the selected column after a user input, while the rest of the columns still print as "X". This game holds values I have set in each column, but does not print them on the screen. When the user selects a column, I need it to print showing the value that column is holding while the rest of the columns still print "X" so they do not reveal what they have. I am new to this, thank you for your help.
This is the function where I think the problem is. If you look, you will see that I have the if statement "if (isCovered) - then I want it to print the covered version. Then the "else" - which is where I want it to print just the one that was guessed as its actual value. I have tried multiple ways of achieving this with no luck. Is there are way to make it like (!isCovered)? But that doesn't work, because it states it needs to be an array and the function "!" does not work. Right now it just seems like it never prints the "else" statement at all. I have functions that take the user input and compare them to "isCovered" and they work correctly, because the piece moves on the board as it should. I just cannot get it to print the actual value instead of an "X". Thank you for any help and if further information would be helpful, please let me know. It is due today unfortunately I only had a few days to work on it and have been working constantly on it.
public static void PrintRevealBoard(int[][] myArray,Boolean[][] isCovered)
{
int i, j;
for (i = 0; i<myArray.length ; i++ ) { // array.length = max rows
System.out.print((i+1) + " ");
for(j = 0; j <myArray[0].length; j++) { // array[0].length = max
cols
if(isCovered[i][j]){
System.out.print(GetRollColorCovered(myArray[i][j]) + " ");
} else {
System.out.print(GetRollColor(myArray[i][j]) + " ");
}
}
your main module is kinda messy. And I don't know how GetRollColor(dice) works. Anyway as I understand you have a two dimensional array and you want to show only a specific value. Seems like u want to show the entire input column.
use this to update isRevealed() after the input of inputCol.
public static Boolean[][] updateRevealed(Boolean[][] isRevealed, int inputCol){
for(int i=0;i<isRevealed[inputCol].length;i++)
isRevealed[inputCol][i] = true;
return isRevealed;
}
update like this,
isRevealed = updateRevealed(isRevealed,inputCol);
your printRevealBoard is almost correct. Just remove the first line. It doesn't make sense and you don't want it as I see
int isRevealed = inputCol;
I don't know how your array looks like. But because of the first for loop u will definitely get an
index out of bounds exception
loop runs until I becomes myarray.length. and in the next loop you access index I of myArray. Exception will be thrown if I=myArray.length. u gotta fix it. If any problem occurs lemme know.
thankyou
edit:
try this for printRevealBoard
public static void printRevealBoard(char[][] myarray , Boolean[] []isRevealed){
for(int i=0;i<myarray.length;i++){
for(int j=0;j<myarray[0].length;j++){
if (isRevealed[i][j]) System.out.print(myArray[i][j] + " ");
else System.out.print("* ");
}
System.out.println();
}
}

ArrayList with formatting

Struggling with my ArrayList code.
I needed to generate 20 random numbers between 1 and 200.
It works but when I show all in array list it, it all comes out horizontal
(ie: [190.9873874849,3.45694033,67.900034...] and SUPER long. It needs to have each number print out in a list format, with the only four digits after the decimal. (%10.4)
I tried this:
System.out.printf("%10.4", num[0]);
which works for the formatting but I can't seem to get the whole arraylist to work.
My array is this:
ArrayList<Number> num = new ArrayList<Number>();
for (int i = 0; i<20; i++) {
num.add(Math.random() *200 +1);
}
It works like I said for getting and listing the numbers -- but not in the "correct" way.
I also have to save the numbers to a file, and be able to let the user choose an index for them and tell them their number they chose from the file, which I am also struggling with.
Any help would be amazing!!!
[EDIT]
This worked (from Ole V.V.):
for (int i = 0; i<20; i++) {
num.add(Math.random() *200 +1);
System.out.printf("%10.4f%n", num.get(i));
[ADDITIONAL]
**I have to post here and can't make a new question because some jerk downvoted me? **
I have all of the numbers in my array read in and saved to a text file (with the right formatting!) but now I have to be able to ask the user for an index, and be able to find the object according to that index... but it isn't working!
I don't know how to assign indexes to variables when the numbers are no longer in array format (they're in a column similar to what is in the column).
Here are a couple of options. First, you may use a for loop like the one you already have:
for (int i = 0; i < 20; i++) {
System.out.printf("%10.4f%n", num.get(i));
}
A terser option is:
num.forEach(n -> System.out.printf("%10.4f%n", n));
In both case the output goes like
186.8143
129.4201
169.7405
...
Your format string, %10.4, was almost correct. You need to add f for formatting a floating-point number. I also added %n for a line break after the number. In Java num[i] works only for arrays, not for ArrayList, you need num.get(i).
You need to trim the extra digits by this simple trick.
double number = Math.random()*200 + 1;
number = (long)( number * 10000 );
number = number / 10000;

homework and overloading in java

Ok so this is my homework assignment, and I am having a heck of a time figuring out how to correctly use overloading to allow for a certain number of terms to print out.
"Create a class that contains a method that accepts an integer from the user to display the next 5 terms in the following pattern: (n-7) * 3.
So, if the user enters 5, the output should be:
-6
-39
-138
-435
-1326
Add an overloaded method so the user can enter how many termss they want to print out in a pattern:
So, the user would enter 5 as the starting number and 3 as the number of terms to print out in the pattern.
The output would be:
-6
-39
-435
Add different method that displays the formula and provides calculation to the formula: (should get starting number from user input) and prints out the next 5 terms.
(5-7) * 3 = -6
(-6-7) * 3= -39
(-39-7) * 3 = -435
Add an overloaded method that displays the formula and the calculation to the formula and takes in how many times it should print: (should get from user input).
For example: User enters 5 as the starting number and print out 4 times.
(5-7) * 3 = -6
(-6-7) * 3= -39
(-39-7) * 3 = -435
(-435-7) * 3 = -1326
Specifics:
You have a separate class that contains all your methods.
You should have 4 methods in this class.
Your main should call these four methods getting user input where appropriate.
"
I'm not asking for anyone to do this for me, I just would appreciate a steer in the right direction.
At the moment trying to collect the number of terms wanted by the user in the main class then pass it to the Numberpattern class and then from their have the program determine which Calc method to use is not working.
Okay i feel dirty for doing your homework for you but i'll get you started
the first method is
public void printPattern(int n){
int prevAnswer = n;
for(int i =0; i < 5; i ++){
int newAnswer = (prevAnswer - 7) * 3;
System.out.println(newAnswer);
prevAnswer = newAnswer;
}
}
The first overload is
public void printPattern(int n, int c){ //this is the overload
public void printPattern(int n){
int prevAnswer = n;
for(int i =0; i < c; i ++){ // i < c to print that many numbers in the sequence
int newAnswer = (prevAnswer - 7) * 3;
System.out.println(newAnswer);
prevAnswer = newAnswer;
}
}
To Overload a method simply provide different parameters and write the extended new functionality
By overloading a method, you are using the same methods with different parameter lists. This allows the program to decide which method is best to be used with only one call of that method name.
It looks like your first method would have a loop of a fixed number and only one parameter (n). Your second method will have the same name, but now allow for two parameters - the (n) and the number of times to loop.
public static void nextTerms (int n) {
Your fixed count loop and print out of n code...
}
public static void nextTerms (int n, int loopCount) {
Your changeable loopCount count loop and print out of n code...
}
To run that nextTerms method, your main Class could either call:
nextTerms(5);
or
nextTerms(5, 3);
The program will then decide which of the two nextTerms methods are appropriate.
For more information, I suggest - http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Cheers!
Chris

Printing a square of stars in Java

Hi I have been given a task for my course and it is to create an algorithm to make a 5 by 5 square like below:
*****
*****
*****
*****
*****
I've spent hours attempting to do it and read tutorials and books. It's so frustrating as I know it must be so easy if you know what you are doing. Can anyone give me any guidance as to where to start?
You probably know and understand how to create a "Hello World" style program in Java.
Now think - how would you go about having that same program print 5 times "Hello World"?
After that, think about how you would make it write N times "Hello World".
After that, think about how you would output a series of N stars.
Good luck!
Seems like you should have a variable x equal to the dimension (5). A for loop i that loops from 1-x. In it a for loop j that loops from 1-x. The j loops outputs *, or appends * to a string. After the j loop, the i loop does a new line.
This solution will allow for a square grid of any size.
int size = input;
for (i=0; i<size; i++){
for (j=0; j<size; j++){
// output a single "*" here
}
// output a new line here
}
If I got you right, then it's about a NxN square with a given N. Your question is just about N := 5, but your comments let me assume that you've to program a more general solution.
Split the work that have to be done into more basic and smaller problems:
create a String that contains * N times.
call System.out.println() with the generated String N times
This will work for you as well, but the professor will frown that you found the answer online and did not think of it yourself.
System.out.println("*****\n*****\n*****\n*****\n*****");
Here's how I did it:
class Main {
public static void main(String[] args) {
int size = 25;
int pos = 0;
for(int i = 0; i<size; i++){
if(pos % 5 == 0){
System.out.println();
}
System.out.print("*");
pos++;
}
}
}
If I understood correctly, what you need is a console output with 5 lines of stars.
You can outpt text to console with System.out.print() or System.out.println() with the second option making a line break.
As you have to repeat the output, it is advisable to do enclose the output statement in a loop. Better in a nested loop to separate the x and the y axis.
In order to make the output modifiable - for the case you will need to output a 6x6 or 12x15 square tomorrow without any code modification, I would make the limits of the loop parametrized.
All in all, something like this :
public void printStartSquare(int width, int height){
for(int i = 0; i < height;i++){
for(int j = 0; j < width;j++){
System.out.print("*");
}
System.out.println("");
}
}

Categories