using nested for loops statements to draw triangles of ""s. The number of ""s on the last row is input from the user (valid range: 5 to 21). the out put should look like this:
Sample output:
How many stars/last row (5-21)? 25
Out of range. Reenter: 7
*
**
***
****
*****
******
*******
so far this is what i have for the code. I don't know how to get it to look like a triangle. any help would be great.
import java.util.Scanner;
public class Lab7_2{
public static void main(String[] args){
//declarations
Scanner input= new Scanner(System.in);
int how_many;//num of triangles
int m; //constant
int c;//constant
int rows;//row
//prompt for input
System.out.println("Drawing triangles program.");
System.out.println("==============================");
System.out.println("How many triangles?");
how_many=input.nextInt();
System.out.println("How many stars/last row (5-21)?");
rows=input.nextInt();
while(rows<=5||rows>=21){
System.out.println("Out of range. Reenter: ");
rows=input.nextInt();
}
for(m=1;m<=rows;m++){
for(c=1;c<=m;c++){
System.out.println("*");
System.out.println();
}
}
}
}
To center a line, use this:
private static String center(String line, int length) {
StringBuilder newLine = new StringBuilder();
for (int i = 0; i < (line.length() - length)/2; i++)
newLine.append(" ");
}
newLine.append(line);
return newLine.toString();
}
Also,
System.out.println();
prints a line break after each string, which is not what you intend.
Fixed code:
private void printTriangle(int base) {
StringBuilder currentStars = new StringBuilder();
for (int currLine = 1; currLine < base; currLine++) {
currentStars.append("*"); // Don't create a new String, just append a "*" to the old line.
//if (currLine % 2 == 1)
// System.out.println(center(currentStars.toString(), base)); // For centered triangle
System.out.println(currentStars.toString()); // For non-centered triangle
}
}
You are using a println statement to print your stars, as such each will be on its own line no matter what
System.out.println("*");
You want a print statement instead
System.out.print("*");
Additionally inside the star printing loop you have an extra System.out.println(); putting a blank line in, that should be outside the inner for loop
for(m=1;m<=rows;m++){
for(c=1;c<=m;c++){
System.out.println("*"); <-- println always starts a new line, should be print
System.out.println(); <--- shouldn't be within inner loop
}
<--- println() should be here to advance to the next line of stars
}
println() always starts a new line after the output. Try print instead and then one println() after the inner loop.
Just fix your for loop as
for (m = 1; m <= rows; m++) {
for (c = 1; c <= m; c++) {
// first print the * on the same line
System.out.print("*");
}
// then move to the next line
System.out.println();
}
Notice, that you need to use System.out.print() (that does not write a new line \n to the output stream) for the asterisks * to get printed on the same line.
I believe this is the most efficient and simple way to do it, saves having to call the print/println method hundreds of times when playing with larger pyramids.
String out;
for (m = 0; m < rows; m++) {
out = "";
for (c = 0; c < m; c++) {
out+="*";
System.out.println(out);
}
}
Basicly your string is "", and you add a "*" after every time you print it to the next line.
Related
The code I wrote for a homework just won't work, it would end up crashing my IntelliJ IDEA. Tried it on Eclipse and does the same thing. I can't figure out why my code doesn't work... Can you help me figure it out?
import java.util.*;
public class mainClass {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("how many rows do you want");
int rows = s.nextInt();
int spaces;
System.out.print("what character do you want");
char ch = s.next().charAt(0);
for(int count = 1; count<= rows; count++) {
for(spaces = rows -1; spaces<=rows; spaces--) {
System.out.print(" ");
}
for(int stars =1; stars<=rows; stars= stars + 2) {
System.out.print(ch);
}
System.out.println("");
}
}
}
The problem is with your second for loop:
for(spaces = rows -1; spaces<=rows; spaces--)
This will set spaces to rows - 1 and then keep looping while spaces is less than rows, which will always be true because spaces only ever gets smaller. I expect what you meant was more along the lines of
for(spaces = rows -1; spaces > 0; spaces--)
In the code below I have created a program that prints a triangle based on the number that the user inputs for the number of lines.
My questions is this: I am doing all of the computing in the main method, however how would I go about this by splitting this program up and putting the loops in their own method and calling it into the main method?
public class Triangle {
public static void main(String[] args) {
//declare a scanner for user input
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of lines: ");
int numLines = input.nextInt();
//include an if statement to make sure that the number of lines that
the user inputs is greater than zero
if (numLines <= 0)
{
System.out.println("Number of lines is negative. Exiting.");
System.exit(0);
}
//This for loops prints one line for each iteration.
for(int i=0;i<numLines;i++)
{
//This for loop takes care of the preceding spaces in each line.
for(int j=0;j<numLines-i-1;j++)
System.out.print(" ");
//This for loop prints the required number of characters in each line.
for(int k=0;k<=i;k++)
System.out.print("* ");
//We are done with a line. Moving on to the next one.
System.out.println();
}
}
}
You can also do it like this:
import java.util.Scanner;
public class Triangle {
// declare a scanner for user input
Scanner input = new Scanner(System.in);
public int getInput() { // method to take user input
System.out.print("Enter the number of lines: ");
int numLines = input.nextInt();
// include an if statement to make sure that the number of lines that
// the user inputs is greater than zero
if (numLines <= 0) {
System.out.println("Number of lines is negative. Exiting.");
System.exit(0);
}
return numLines;
}
public void printTriangle() {
int numLines = getInput();
// This for loops prints one line for each iteration.
for (int i = 0; i < numLines; i++) {
// This for loop takes care of the preceding spaces in each line.
for (int j = 0; j < numLines - i - 1; j++)
System.out.print(" ");
// This for loop prints the required number of characters in each
// line.
for (int k = 0; k <= i; k++)
System.out.print("* ");
// We are done with a line. Moving on to the next one.
System.out.println();
}
}
public static void main(String[] args) {
Triangle obj = new Triangle(); // create object
obj.printTriangle(); // call using object
}
}
Here we are creating two functions :
getInput() To take input from user and return numLines to the caller.
printTriangle() To print pattern
In the end we are creating an object of the Triangle class and calling the printTriangle().
Triangle obj = new Triangle(); // create object
obj.printTriangle(); // call using object
I am trying to terminate my code when "END" is input into the console, however my code wont play fair and I can't seem to see where it is going wrong, btw I haven't learnt how to debug as of yet so this has largely got to do with why i can't figure it out. please do help if you can.
import java.util.*;
class Main
{
public static void main(String args[])
{
int j = 0;
while (j++ <= 3) {
// Create Scanner object to take input from command prompt
Scanner s=new Scanner(System.in);
// Take input from the user and store it in st
String st = "";
while (!st.equals("END")) {
{
st=s.nextLine();
// Initialize the variable count to 0
int count=0;
// Convert String st to char array
char[] c=st.toCharArray();
// Loop till end of string
for(int i=0;i<st.length();i++)
// If character at index 'i' is not a space, then increment count
if(c[i]!=' ') count++;
// Print no.of spaces
System.out.printf("[%4d] spaces in ", +(st.length()-count));
// Print no.of spaces
System.out.println('"' + st + '"');
}
j++;
}
}
}
Since you have while (j++ <= 3) { ... } your program will end if you enter "END" two times.
Because you have two while loops nested. You input "END" in the second while loop and after that the second loop ends that's correct. But as you see, after it ends it will start the first loop which is while (j++ <= 3) { and in this while loop it waits for an input from user 3 times, which corresponds to Scanner s=new Scanner(System.in);, therefore it is normal for your program not to exit. If you want your program to finish after some input you may want to use System.exit(-1); command. I've added code according to your comments.
import java.util.*;
class Main {
public static void main(String args[]) {
int j = 0;
while (j++ <= 3) {
// Create Scanner object to take input from command prompt
Scanner s = new Scanner(System.in);
// Take input from the user and store it in st
String st = s.nextLine();
if (!st.equals("END")) {
// Initialize the variable count to 0
int count = 0;
// Convert String st to char array
char[] c = st.toCharArray();
// Loop till end of string
for (int i = 0; i < st.length(); i++)
// If character at index 'i' is not a space, then increment count
{
if (c[i] != ' ') {
count++;
}
}
// Print no.of spaces
System.out.printf("[%4d] spaces in ", +(st.length() - count));
// Print no.of spaces
System.out.println('"' + st + '"');
} else {
System.exit(-1);
}
}
}
}
I have just add an if condition without using loop.
public static void main(String args[]) {
int j = 0;
while (j++ <= 3) {
// Create Scanner object to take input from command prompt
Scanner s = new Scanner(System.in);
// Take input from the user and store it in st
String st = "";
st = s.nextLine();
if (st.equalsIgnoreCase("END")) {
j = 5;
}
// Initialize the variable count to 0
int count = 0;
// Convert String st to char array
char[] c = st.toCharArray();
// Loop till end of string
for (int i = 0; i < st.length(); i++) // If character at index 'i' is not a space, then increment count
{
if (c[i] != ' ') {
count++;
}
}
// Print no.of spaces
System.out.printf("[%4d] spaces in ", +(st.length() - count));
// Print no.of spaces
System.out.println('"' + st + '"');
j++;
}
}
What I do basically when I get the input end I just change the value of j to 5 so that the first loop will be terminated. and stop taking inpu.
Do you want this type of solution or you want you need to take input 3 times?
I have the basics, but I need to make it so that my program will work without printing the unused letters of the alphabet at the end, say my sentence is "dog" I would want the output to be: D-1
O-1
G-1, instead of A-0 B-0 D-1, and so on. Thanks for any help provided, it is greatly appreciated.
what I have so far is:
package as10;
import java.util.*;
public class as
{
private static void countLetters(String sentenceString)
{
int[] array = new int[26];
sentenceString = sentenceString.toUpperCase();
for (int i = 0; i < sentenceString.length(); ++i)
{
if (sentenceString.charAt(i) >= 'A' && sentenceString.charAt(i) <= 'Z')
{
++array[sentenceString.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println((char) ('A' + i) + " - " + array[i]);
}
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
String letterString;
while (true)
{
System.out.println("Enter a line of text: ");
letterString = kbd.nextLine();
System.out.println("Letter Frequencies: ");
countLetters(letterString);
break;
}
kbd.close();
}
}
so, basically, you want to opt out all chars if counter is 0.
In other words, you will need an if statement around print line and only perform system output if relevant array value is non-zero.
Above statement is in pure English. It is again your assignment to convert that sentence into java, as I refuse to do your homework on your behalf.
Does it sound fair ? :)
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?
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
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();
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.
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()
Use System.out.println to print the word on separate lines:
System.out.println(data)
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();
}
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();
}
}