I'm trying to make a 'histogram' in java and running into trouble with some formatting. I've got the below loop for printing a frequency distribution table:
for (int i = 0; i < 10; i++) {
char asterisk[] = new char[frequency[i]];
Arrays.fill(asterisk, '*');
System.out.println(asterisk);
freqTable = bins[i] + "\t";
System.out.println(freqTable);
}
But this produces an output like:
************
1-10
**********
11-20
**********
21-30
And i'd like to have it print like this:
1-10 ************
11-20 **********
21-30 **********
No idea how to get it to do this! Tried using toString(), didn't get anywhere though.
Thanks in advance!
You need to re-order the statements that print your items. I would recommend using a single println at the end of the loop:
for (int i = 0; i < 10; i++) {
char asterisk[] = new char[frequency[i]];
Arrays.fill(asterisk, '*');
System.out.println(bins[i] + "\t" + asterisk);
}
Simply change the order and using print instead of println
for (int i = 0; i < 10; i++) {
char asterisk[] = new char[frequency[i]];
Arrays.fill(asterisk, '*');
freqTable = bins[i] + "\t";
System.out.print(freqTable);
System.out.println(asterisk);
}
or alternative use System.out.printf
System.out.printf ("%s %s%n", freqTable, asterisk);
or a single System.out.println
System.out.println(freqTable + asterisk);
Related
I know I'm being a little dumb about this, but I figured id take a break for a few mins and ask this question. I'm trying to add a countdown feature to an input box. The problem is that its doing the input amount a squared number of times when all im really trying to is increment a variable thats called inside the loop itself. I'm certain it will come to me, but getting someone else perspective helps.
String propertyNumber = JOptionPane.showInputDialog("Enter Numer of Properties...");
int propNumber = Integer.parseInt(propertyNumber);
numOfProperties = new float[propNumber];
for(int i= 0; i < propNumber; i++) {
for(int a = propNumber; a >= 0; a--) {
String propertyVal = JOptionPane.showInputDialog("Enter each property value for the " + propNumber + " Properties you listed. You have " + a + " inputs left.");
numOfProperties[i] = Float.parseFloat(propertyVal); //takes property value info and stores them inside the property number array
}
}
Suppose, propNumber = 3. Since, you are using nested loops it will work as follows :
Take the case of the nested loop first :
for(int a = propNumber; a >= 0; a--) {
}
Given propNumber is 3, the code inside it will be executed 3 times.
Take the case of the main loop :
for(int i= 0; i < propNumber; i++) {
//another loop inside
}
As the code inside the main loop will be executed 3 times, the loop inside it will get executed 3 times as well. 3*3 = 9.
As I mentioned in the comments, you do not need a nested loop. I believe you want a single loop and a should be calculated from the number of properties and the current index i. Like,
for (int i = 0; i < propNumber; i++) {
int a = propNumber - i;
String propertyVal = JOptionPane.showInputDialog("Enter each property value for the "
+ propNumber + " Properties you listed. You have " + a + " inputs left.");
numOfProperties[i] = Float.parseFloat(propertyVal);
}
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++){
I want my arraylist to print elements like this:
1894,
1895,
1896,
etc..
but i am getting 1894, 1895, 1896
ArrayList<Integer> years = new ArrayList<Integer>();
int j;
for (j = 1894; j < 2014; j++)
{
years.add(j);
//comboyears.addItem(j);
}
System.out.println(years);
You are actually printing years, which will print the String returned by the toString() of the ArrayList.
You are getting the array multiple times, because the print statement is inside the for loop, so each iteration it will print the array (with the element recently added). To print the array just one time, move the print outside the loop.
If you want to print each element without [] you could try the following:
for (Integer i : years) {
System.out.print(i + ", "); // This will print a comma at the end
}
or this, to avoid printing an extra comma ,:
for (int i = 0; i < years.size() - 1; i++) {
System.out.print(years.get(i) + ", ");
}
System.out.println(years.get(years.size() - 1));
Output:
1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, ...
Edit:
You can also override the toString method while creating a new instance of ArrayList:
ArrayList<Integer> years = new ArrayList<Integer>()
{
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size() - 1; i++) {
sb.append(get(i));
sb.append(", ");
}
sb.append(get(size() - 1));
return sb.toString();
}
};
So you can print the array System.out.println(years); in the way you want.
Edit 2:
Since you have edited the question, which I would encourage you not to do, you can do this adding a new-line character \ n or changing print by println:
for (int i = 0; i < years.size() - 1; i++) {
System.out.println(years.get(i) + ", "); // or concatenate with ", \n"
}
System.out.println(years.get(years.size() - 1));
If you are overriding toString method from ArrayList you can append a new-line character too. Replace `sb.append(", ") with
sb.append(", \n")
This is expected if you keep your System.out.print inside the for loop. You are printing out the entire list every time you add an element.
If you only want to print it when you're done adding, move the System.out.print after the end of the for loop.
ArrayList<Integer> years = new ArrayList<Integer>();
int j;
for (j = 1894; j < 2014; j++)
{
years.add(j);
System.out.println(years.get(j) + ","); // get elements from 1894 to 2014
}
I have a program I'm working on that I'm stuck on and can't really figure out. Basically, I'm supposed to input a word, and have the word be encased in a box of asterisks, which is the main objective. The actual prompt says: Read a string from the keyboard. Output the string centered inside of a box as shown below. The box needs to be resized on each run to assure that it has the correct spacing.
Ex.
Here is my code:
import java.io.*;
import java.util.*;
public class Prog600a
{
public static void main(String[] args)
{
for(int i = 1; i<=3; i++)
{
Scanner kbReader = new Scanner(System.in); //Allows input
System.out.print("Enter a string: ");
String word1 = kbReader.nextLine();
int len1 = word1.length();
for(int x = 0; x<=len1; x++)
{
System.out.print("*");
}
System.out.println();
System.out.print("*");
for(int x = 0; x<len1; x++)
{
System.out.print("\t");
}
System.out.print("*");
System.out.println();
System.out.println("* " + word1 + " *");
System.out.print("*");
for(int x = 0; x<len1; x++)
{
System.out.print("\t");
}
System.out.print("*");
System.out.println();
for(int x = 0; x<len1; x++)
{
System.out.print("*");
}
System.out.println();
}
}
}
I'm using the string method length to determine how long the string is, and print asterisks according to that. However, I can't seem to get the spacing, and my output looks nothing like the one shown. I've been experimenting with the code for a few hours (which is why it's a bit long and may be inefficient ), but can't really seem to get it. The spacing isn't right, and I don't really know how to correctly resize the box on each run. Can someone please provide some guidance? Thanks for all the help!
I spot only tiny problems:
You don't print enough asterisks in the top and the bottom (make it < len1 + 4)
You print tabs instead of spaces (change "\t" to " ").
You don't print enough spaces, change those loops to < len + 2
That's all. My output for input test:
********
* *
* test *
* *
********
Stack Overlow isn't for doing your homework for you. But, I will give you some pointers:
Look at repeat.
A tab character is 4-8 characters long, depending on how you're viewing it. '*' is one character long.
for(int i = 1; i < 12; i++)
{
for(int k=11; k > i; k--)
{
System.out.print("*");
}
System.out.print("\n");
}
I have the code above which displays a design like this:
**********
*********
********
*******
******
*****
****
***
**
*
I am wanting to swap it so that it looks like this:
**********
*********
********
*******
******
*****
****
***
**
*
I know that I need to use a loop and System.out.print(" ") in some way to leave spaces.
Whats the best approach to use? I created two separate loops, but with the next line commands this wont work in two loops. How would I integrate that into one loop?
For the second "picture": you'll have to print a variable number of spaces before the "*". That can be accomplished by using another loop before the loop that prints the "*", and knowing that every time you print a line, the number of spaces printed is incremented by one, and the number of asterisks is decremented by one.
EDIT :
Here's a hint, to get you started. Fill-in the blanks (and remove the comments):
int delta = /*fill*/;
for (int i = 0; i < /*fill*/; i++) {
for (int j = 0; j < /*fill*/; j++) {
System.out.print(" ");
}
for (int j = 0; j < /*fill*/; j++) {
System.out.print("*");
}
delta += /*fill*/;
System.out.print("\n");
}
Use String.format to left pad your string with spaces.
Do it using a 2-D array!!! Its very simple and efficient that way!!
For the second result:- Put '*' in places if row_no <= column_no (the half matrix above diagonal plus the diagonal elements) else put a space " " in other places. Run this in loops for row and column. Then print the 2-D array row wise.