• 0

[Java: Arrays] Using printf


Question

I am trying to using the prinf method while printing values of an array. Below is an example of what I'm trying to obtain in formatting output:

post-67678-0-89881600-1299211348.jpg

Here is a snippet of code I'm trying to use the printf method with:

     		for (int row=0; row < payScaleTable.length; row++) {											 
						 System.out.print("Person printPerson);					
						 printPerson = printPerson + 1;

         		for (int col=0; col < payScaleTable[row].length; col++)

						System.out.print("\tayScaleTable[row][col] + "\t");	
						System.out.println();
                         }

Anytime I start adding the prinf method to that statement inside the for loop, I start getting "Array out of bounds" errors.

Link to comment
https://www.neowin.net/forum/topic/980160-java-arrays-using-printf/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

The code you posted is correct. Out-of-bounds error would have nothing to do with the use of printf. Could you show how you use printf, i.e. the code that causes the out-of-bounds error?

A possible source of bugs here is the variable printPerson, which duplicates row as a loop counter. Consider eliminating printPerson and using row instead.

  • 0

Ok, I'm off to a slightly better start now but I'm still having trouble keeping everything aligned in the long run.

For example if you look at the very top of the first picture I posted (what the output should actually be), I can't seem to keep things aligned in the long run. For example here is what I have so far when trying to get that first block.

			
 System.out.println("Summerrnship Salary Information: "); 
			  System.out.print("\t\t		  while (numberOfYears >= printYears) {		

			  		System.out.printf("Year\t", printYears);
					printYears = printYears + 1;
				}

			  System.out.println("");

			   for (int row=0; row < payScaleTable.length; row++){
        			for (int col=0; col < payScaleTable[row].length; col++)

           			 payScaleTable[row][col] = 1000 + (int)(Math.random() * ((20000 - 1000) + 1));			}	 																											 

     			for (int row=0; row < payScaleTable.length; row++) {											 
						 System.out.print("Person printPerson + "\t");					
						 printPerson = printPerson + 1;

         		for (int col=0; col < payScaleTable[row].length; col++)

						System.out.printf("$%,6d\t\tayScaleTable[row][col]);	
						System.out.println();
      		}

If that code is run, over time the year and the numbers start to get slowly separated. Like this:

post-67678-0-60715600-1299354142.jpg

  • 0

It is amazing how easily I have been missing tiny little things like that which end up making a huge difference. Can I get rid of the extra space between the $ and the numbers if it is a number like $ 1,799? I know I have a 6 built into the printf method, but I just thought I would ask because it would look cleaner if for example I had $1,799 instead of $ 1,799.

  • 0

The '$' is not part of the number so it's not right-aligned like the number is. Off the top of my head, I'd say you could pre-convert the number to a string, insert the '$' at the beginning and then output the whole thing right-aligned, as a string.

See http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html for all the details, maybe there's an even better solution there.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Report: Trump's T1 Mobile off to a rocky start with messy pre-orders by David Uzondu You might have heard by now that The Trump Organization, spearheaded by President Trump's sons, Donald Trump Jr. and Eric Trump, is launching yet another product to add to the collection. This time, it is a gold smartphone, the T1, and a companion wireless service. The whole operation is being pushed with the usual "America-first" bravado, but it seems they forgot to get the basics right. If you thought you could just hop online and secure your patriotic pocket computer, you are in for a nasty surprise, as the whole process appears to be fundamentally broken. A new report from 404Media details this chaos perfectly, as one of their writers tried to order one of the T1 phones. The goal was simple: pay the $100 preorder deposit and see what this thing is all about when it ships. What happened next was a masterclass in how not to conduct e-commerce. The website crashed, booted him to an error page, and then, for good measure, charged his credit card the wrong amount entirely, taking $64.70. And get this, he received a confirmation email saying his order would ship... despite never once being asked for his shipping address. It is, in his words, the "worst experience I've ever faced buying a consumer electronic product". To add insult to injury, when he tried to log into the new account, the site prompted him to create, and he was immediately met with yet another error page, locking him out. The shoddy experience is not just limited to the checkout. Neowin found a bunch of errors on the official product page. Sure, it boasts a big 6.8-inch Punch Hole AMOLED display with a 120Hz refresh rate and a 50MP main camera, which sounds nice on paper. But then you notice the company completely forgot to mention what processor powers the phone, which is probably a MediaTek. At one point, the page bizarrely listed a "5,000 mAh long life camera," though that has since been fixed. By the way, there's good reason to doubt that this phone will be made in America, despite the press releases insisting it will be. Sourcing all the necessary components without using foreign parts is unbelievably difficult and expensive, something even Apple does not do. The more likely scenario, according to Max Weinbach, is that this is simply a reskin of a much cheaper device, maybe the T-Mobile REVVL 7 Pro 5G, which retails at a fraction of the T1's $499 asking price. The T1 Mobile joins a sprawling collection of other products likely aimed at the same loyal customer. The catalog of gear for this audience already includes the gold "Never Surrender" sneakers, the "God Bless the USA" Bible, "Victory47" perfume, digital trading cards, $TRUMP memecoins, and more. It is still very early days, of course, and while one might forgive some teething issues for a new venture, this initial preorder phase has been exceptionally chaotic. Hopefully, things will become much clearer once there is a firm launch date and a physical product to test. Do you plan to buy the T1 and move to Trump Mobile?
    • Is this release set for the end of this year or for next year?
    • Windows 10 KB5063159 fixes bug that wouldn't let some Microsoft Surface devices boot by Sayan Sen Microsoft released Windows 10 Patch Tuesday updates for the month last week. The one for Windows 10 under KB5060533 / KB5060531 / KB5061010 / KB5060998 introduced a bug that would not let Surface Hub v1 devices start due to a Secure Boot validation issue. As such, Microsoft had paused the update similar to the compatibility blocks or safeguard holds it applies for major feature updates as well. This bug was uncovered after the update went live, as Microsoft later added it to the list of known issues for that update and it also put up a big notice in bold. It wrote: Earlier today, the company released an out-of-band (OOB) update to address the issue. It has been published under KB5063159 and is only being offered to Surface Hub v1 devices instead of the buggy KB5060533 Patch Tuesday one. In the description of the new OOB update, Microsoft writes: You can find the support article for KB5063159 here on Microsoft's website. It is downloaded and installed automatically but users can also manually download it from the Microsoft Update Catalog website.
    • I thought I saw that one, and yeah, it was awhile ago, too..
    • Jumping unicorns says that I forgot you. I never grunt.
  • Recent Achievements

    • Week One Done
      korostelev earned a badge
      Week One Done
    • Week One Done
      rozermack875 earned a badge
      Week One Done
    • Week One Done
      oneworldtechnologies earned a badge
      Week One Done
    • Veteran
      matthiew went up a rank
      Veteran
    • Enthusiast
      Motoman26 went up a rank
      Enthusiast
  • Popular Contributors

    1. 1
      +primortal
      687
    2. 2
      ATLien_0
      268
    3. 3
      Michael Scrip
      184
    4. 4
      +FloatingFatMan
      177
    5. 5
      Steven P.
      140
  • Tell a friend

    Love Neowin? Tell a friend!