Win a copy of Python Continuous Integration and Delivery this week in the Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
Bartenders:
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

How to make code move to next line (/n) of output in code? (Loops, Java)  RSS feed

 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good afternoon! I want my code to output a word length() number of times. The following code is the second class of my code (I can supply the first upon request but it only sets up a scanner to allow user input and assigns that phrase as String s.), which works perfectly fine to accomplish (for the most part what I want.

However, when my code runs (with test value "hippo"), it returns-
hippo hippo hippo hippo hippo
as opposed to-
hippo
hippo
hippo
hippo
hippo

What can I add that will change the output to putting each iteration of word on a new line? Thank you!

 
Jeremiah Waters
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much! Turns out I was entering the wrong slash
 
Marshal
Posts: 63409
205
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are better off using printf and the %n tag.
Don't use the + or += operators on Strings in a loop; that can cause very slow execution. Use a StringBuillder object instead.
 
Rancher
Posts: 1930
15
Android Eclipse IDE Java Java ME
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two more thoughts

fin can be a method local variable doesn't need to be instance level variable

and



the following might be a better approach



In the above approach word length will be calculated only once not in every loop iteration.


 
Campbell Ritchie
Marshal
Posts: 63409
205
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a potential problem if you don't use word.length(). What happens if word is reassigned in the loop? I think most of us would prefer to use i < word.length()
 
Evil is afoot. But this tiny ad is just an ad:
Become a Java guru with IntelliJ IDEA
https://www.jetbrains.com/idea/
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!