I'm having trouble figuring out This last pattern in a java assignment. I know I'm close but I can't figure it out here's my code:
public static void main(String[]args){
System.out.println("Pattern D:");
for (int i = 6; i>=1; i--) { // row
int x = 6; // Counter?
for (int j = 1; j<=i; j++){ //column
System.out.print("");
x--;
}
for(int k=1;k<=i;k++) {
System.out.print(x);
}
System.out.println();
}
}
I understand that the outer loop is the rows and the inner the columns, but that's not the part I have wrong. My pattern it self is right but not the out put of the numbers.
I can't put my output on here because it won't format right. But if you copied my code exactly instead of a line of 0,then 1, then, 2... etc, I'm trying to get 1 2 3 4 5 6 on the top line, then 1 2 3 4 5, the next line and so on...
You were actually very close to the correct pattern, you just added a little too much. As a general tip (not always but most of the time), when making these loop patterns you can usually print these patterns using the integers in your loops. I changed your code a little bit to give you the pattern you wanted. You didn't need x as a counter because you can just use your deepest nested loop's integer as a counter, which in how I just adjusted your code is j because it will run for 6 times on the first then 5 on the second and so on. Another extra part that you added was the 3rd nested loop. It essentially did the exact same thing that the 2nd loop does because they both had the condition of running while they were less than i. Well here is the code; I hope my explanation helped.
public static void main(String[]args){
System.out.println("Pattern D:");
for (int i = 6; i>=1; i--) { // row
for (int j = 1; j<=i; j++){ //column
System.out.print(j);
} System.out.println();
}
}
Here is your expect code:
import java.util.*;
public class Test{
public static void main(String[]args){
System.out.println("Pattern D:");
for(int i=6 ;i >= 1;i--){
int k=i;
for (int j=1 ;j<=k; j++){
System.out.print(j);
}
System.out.println();
}
}
}
Turns out I said what I was trying to do earlier wrong. I wanted to right justify the pattern but here is my solution. Sorry for any confusion.
for (i=6;i>0;i--) {
x=6;
for (j=i;j<6;j++) {
x--;
System.out.print(" ");
}
for(k=1;k<=i;k++) {
System.out.print(x--);
}
System.out.println(" ");
}
public class TestPattern {
public static void main(String[] args) {
for (int i = 6; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
Output:
123456
12345
1234
123
12
1
Related
What I have to do is to create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are...
1 uno 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
I do not know why am I getting this error below
http://i.stack.imgur.com/HLIiI.png
Thanks in advanced!
import java.util.Scanner;
public class SpanishNumberss {
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
}
public static void main(String args[]) {
for (int i = 1; i <= 10; i++)
spanishNumbers(i);
}
}
In Java, indexes of an array start with 0, not 1, and run through length - 1, not length.
Adjust your for loop condition in main as follows:
for (int i = 0; i < numbers.length; i++)
You'll need to adjust your other for loop similarly.
Arrays indexes are 0 based (starts from 0 not from 1) . Also you are declaring your array numbers inside the method each time is called just declare as a class variable. So take care that in your example index 0 refers to 1 (uno) and so on.
I made you an example and add 0,"cero"
public class SpanishNumberss {
private static final String[] numbers = {"cero","uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
public static void spanishNumbers(int num) {
//loop here is unnecesary
System.out.println(numbers[num]);
}
public static void main(String args[]) {
//and here in main i call them from 1 to 10
for (int i = 1; i < 11; i++){
spanishNumbers(i);
}
}
}
ArrayIndexOutOfBounds means you have gone out of the boundaries of your array (in your case numbers). What you have to realize is array's are 0 index-based. So in your for loop, you really 0 - 9, not 1-10.
And an even better solution, as #rgettman has posted is to use the length property of the array. So you are not hard-coding in those magic numbers.
Arrays go from 0 to N-1
That's why you're getting that error, change your for cycle to:
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
Your problem is here:
for (int i = 1; i <= num; i++)
Arrays in Java are 0-based. So the valid indices run from 0 to array.length - 1. So an array of length 5 would have the valid indices 0, 1, 2, 3, and 4. Change your loop to the following:
for (int i = 0; i < num; i++)
This will ensure that in your loop i will only have the values from 0 to 9.
your loop should only have the values from 0 to 9:
for (int i = 0; i < num; i++)
first of all i don't think you need a loop in the spanishnumber method...
cos you already know the index of what you are looking...// that's if i understand you
so the only place you need the loop is in the main method...so your code should look like dis
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
spanishNumbers(6);
}
}
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
System.out.println(numbers[num -1]);
}
I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){
Guys i would like to ask how to get rid of the "and" print on my loop
2 and 4 and <
public static void main(String[] args) {
Methods(5);
}
public static void Methods(int a){
int loops = a/2;
int even = 0;
for(int i = 0; i < loops; i++){
even+=2;
System.out.print(even+" and ");
}
}
it prints
2 and 4 and <<<
Instead i want
2 and 4 <<<
thank you.
Please help me i am beginner T_T
You can do:
public static void Methods(int a){
int loops = a/2;
int even = 0;
for(int i = 0; i < loops; i++){
even+=2;
System.out.print(even);
if (i < loops - 1) {
System.out.print(" and ")
}
}
In other words: as long as i is smaller than loops - 1 (which holds during your entire loop except the last step) you would print out " and ". This ensures the last and is not printed when it goes through the loop the last time.
Test if your index is the last index you would be on, i.e. if i == loops - 1. If so, then just print even instead of even + " and ".
Before entering the loop check if there is an element, print just the first element. Increment i and then for each remaining element always pre-pend " and " first.
int i = 0;
if (i < loops) {
even+=2;
System.out.print(even);
}
i++;
for(; i < loops; i++){
even+=2;
System.out.print(" and " + even);
}
This way you avoid all the checking inside the loop.
Hey I have a question I have been trying to figure out for a couple hours now, I need to use nested loops to print the following
-----1-----
----333----
---55555---
--7777777--
-999999999-
This is what I have so far.
public static void Problem6 () {
System.out.println("Problem 6:");
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
for (int j = 1; j <= 9; j += 2) {
System.out.print(j);
}
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
System.out.println();
}
}
This is what it prints
-----13579-----
----13579----
---13579---
--13579--
-13579-
You have the correct number of dashes, you just aren't printing out the number correctly. Let's examine why that is:
Which loop prints out the numbers?
The 2nd nested for loop.
What does it do?
It prints out j where j ranges from 1 to 9 and j is incremented by 2 each iteration of the loop. In other words, 1, 3, 5, 7, 9, which is confirmed in your output
What do you want it to do?
Well let's look at the desired output. You want 1 to be printed once on the first first line. You want 3 to be printed three times on the third next line. You want 5 to be printed five times on the fifth next line after that. And so on.
Do you notice a pattern? You want that loop we mentioned above to print the same number (1, 3, 5, ... i) as the number of times (1, 3, 5, ... i).
edit Whooops I actually misread the output. My answer is still very similar to before, but I lied about which line you are printing what. It's still 3 three times, 5 five times but different lines. The easiest way to jump from my solution to the actual one is to notice that on the even lines... you do nothing. You could arguably even write your solution this way.
Another tip is that you should just focus on getting the numbers on each line right and the dashes separately. It's likely that you'll screw up the number of dashes when you fix the numbers on each line, but then you'll realize how to fix the dashes easily.
These for loops
for(int i=1;i<=9;i+=2)
{
for(int b=9;b>=i;b-=2)
{
System.out.print("-");
}
for(int j=1;j<=i;j++)
{
System.out.print(i);
}
for(int b=9;b>=i;b-=2)
{
System.out.print("-");
}
System.out.println();
}
print
-----1-----
----333----
---55555---
--7777777--
-999999999-
public class pattern
{
public static void main ( )
{
for (int i = 1;i<=9;i+=2)
{
for(int b = 9;b>=i;b-=2)
{
System.out.print(" ");
}
for(int j =1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
}
}
I have a fairly simple question regarding Java. I am currently learning Java and one of the homework questions has me stumped. The goal is to create a triangle with the little figure. I believe I have the idea down however, I cannot get the whole figure of the guy to move to the right.
The code I have so far is:
public class LittleGuy {
public static final int NUMBER_OF_GUYS = 5; // determines the number of guys.
public static void main(String[] args) {
for (int line = 1; line <= NUMBER_OF_GUYS; line++){
for (int j = 1; j <= (-5 * line + 25); j++){// uses the algorithm.
System.out.print(" ");
}
guy();
}
}
public static void guy(){
System.out.print(" o ******\n /|\\ *\n / \\ *");
System.out.println();
}
}
Basically, the body and the head aren't supposed to be separated. I'm having trouble keeping them together. I am assuming that it is a fairly simple fix I am either unaware of or completely over looking. Any information or thought would be greatly appreciated. Thanks again.
You are only printing out the spaces before the first line of your little guy, inside the guy() method, you are still printing the rest of the guy on the first line.
I'd suggest making a printSpaces(int numSpaces) method which prints numSpaces spaces, and changing the guy method to take the number of spaces to print at the beginning of each line.
public class LittleGuy {
public static final int NUMBER_OF_GUYS = 5; // determines the number of guys.
public static void main(String[] args) {
for (int line = 1; line <= NUMBER_OF_GUYS; line++){
int counter=0;
for (int j = 1; j <= (-5 * line + 25); j++){// uses the algorithm.
System.out.print(" ");
counter++;
}
guy(counter);
}
}
public static void guy(int count){
System.out.print(" o ******");
System.out.print("\n");
for(int i=0;i<count;i++)
System.out.print(" ");
System.out.print("/|\\ *");
System.out.print("\n");
for(int i=0;i<count;i++)
System.out.print(" ");
System.out.print("/ \\ *");
System.out.println();
}
}
The problem was : In the guy() method you use \n to print the guy. But it will not take care of the white-spaces you printed in-order to achieve your algorithm (inside the for loop).
How it was solved : place a counter in the for loop to count how many white-spaces were printed and use that counter in the guy() method to print required white-spaces.