Reputation: 3
I have a Java program that reads from a file like such
6 fun. 3 hello 10 <> 2 25 4 wow!
The number represents how many times the word will be repeated so output would be fun.fun.fun.fun.fun.fun.
hellohellohello
<><><><><><><><><><>
2525
wow!wow!wow!wow!
However, mine is printing all on one line
import java.io.*;
import java.util.*;
public class Words {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("aa1234.txt"));
printStrings(input);
}
public static void printStrings(Scanner input) {
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
}
}
}
I've been playing around with input.nextLine() and whatnot, but don't understand how to get to the next line after it prints the repeated words. Help?
Upvotes: 0
Views: 263
Reputation: 2905
make your function like below
public static void printStrings(Scanner input) {
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
}
}
Upvotes: 0
Reputation: 16
Print a new line after the inner for loop. Something like this
while (input.hasNext())
{
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
}
Upvotes: 0
Reputation: 6887
print one new line after printing all the same words in one line.
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
Upvotes: 1
Reputation: 183
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
Upvotes: 1
Reputation: 128438
Issue:
mine is printing all on one line
Solution:
Because you have used System.out.print()
, using that it will print everything on the same line. If you would want to have a line break then use System.out.println()
Upvotes: 0
Reputation: 3890
You can use System.out.print("\n")
to print a line end.
Like this :
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.print("\n");
}
You can also use the System.out.println()
to print a line and automatically append a line end. For example, build the string before print it :
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= times; i++) {
builder.append(word);
}
System.out.println(builder.toString());
}
Notice the use of StringBuilder, much more faster and consuming less memory than a classical string concatenation.
Upvotes: 0