Stefan P Auckland Stefan P Auckland - 1 month ago 6
Java Question

loop with one new line not multiple JAVA

Java Newbie Here,
So i am attempting to write a program that can set the number of hello worlds, and the number of exclamation points that follow it, entering these value using the command line arguments. i have in a manner done it but the output format is wrong.
Desired result

"Hello World !!!!

"Hello World !!!!"

Attempt 1

"Hello World !

!

!

!" (this continues down)

what I am Getting, attempt 2

"Hello World !!!!Hello World!!!!Hello World!!!!"


my code for Attempt 1


public class NHelloWorldWE {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a = a + 1) {
System.out.print("Hello World");
for (int b = 1; b <= e; b = b + 1) {
System.out.print("!");
System.out.println(" ");
}
}

}
}


My Code for Attempt 2

public class NHelloWorldWE {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a = a + 1) {
System.out.print("Hello World");
for (int b = 1; b <= e; b = b + 1) {
System.out.print("!");
}
}

}

}

Answer

You need to use a new line print:

System.out.println("Hello World");

Like this:

public static void main(String[] args) {
    //
    int n = Integer.parseInt(args[0]);
    int e = Integer.parseInt(args[1]);
    for (int a = 1; a <= n; a = a + 1) {
        System.out.print("Hello World");
        for (int b = 1; b <= e; b = b + 1) {
            System.out.print("!");
        }
    System.out.println();
    }
}

This one will give you a similar result, but with 1 less exclamation mark in each iteration (I believe this is what you are trying to do)

  public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        int e = Integer.parseInt(args[1]);
        for (int a = 1; a <= n; a++) {
            System.out.print("Hello World");
            for (int b = 1; b <= e; b++) {
                System.out.print("!");
            }
        e--;
        System.out.println();
        }
    }
Comments