Rewrite code with two loops and two output statements - java

I am working on completing the summer assignment for my AP Computer Science A class. The base code for the next portion is this:
public class Stars {
public static void main(String[] args) {
System.out.println("*");
System.out.println("**");
System.out.println("***");
System.out.println("****");
System.out.println("*****");
}
}
RESULT:
*
**
***
****
*****
I am supposed to rewrite the code to output the same result, using two loops as well as only two output statements that I will provide below:
System.out.print(“*”);
System.out.println();
I have found one alternative means to do so:
public class StarsLoop {
public static void main(String[] args) {
for (int i = 0; i < 1; i++)
System.out.print("*\n**\n***\n****\n*****");
}
}
Of course, though, this does not include two loops and the two given output statements as is required; however, I can't really seem to think of how I would do so. So, what is a possible way to do so?

You want to print five lines in total, each line consists of the line number star characters. Loop from one to five (inclusive), and inside that loop - loop again, this time the outer number of times printing stars. After that, print a newline. Like,
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
Of course, you could eliminate a loop by accumulating stars in a StringBuilder - and outputing that on each iteration. Like,
StringBuilder line = new StringBuilder("*");
for (int i = 0; i < 5; i++) {
System.out.println(line);
line.append("*");
}

The following code will produce the desired result:
for (int i = 1; i <= 5; i++) // Loop over each asterisks row to be printed
for(int j = 0;j < i; j++) { // Loop over the number of stars to print for the current line. It is based on the current row number
System.out.print(“*”); // Add an asterisks to the current row
}
System.out.println(); // Move to the next line
}

Related

Check number of character from command line

I am trying to solve this question: Write a program that passes a string to the command line and displays the number of uppercase letters in the string.
The test is ProgrammingIsFun, so the count would be three.
Here is what I have so far
public static void main(String[] args) {
int count = 0;
for(int i = 0; i < args.length;i++) {
for(int j = 0; j >= i; j++)
if(Character.isUpperCase(args[i].charAt(j)))
count++;
}
System.out.print("The number of upper cases are: " + count);
}
when this runs it does count the correct number of uppercases but it runtimes when it reaches the end of the characters(16). I can't figure out how to stop the loop right after the last character. I know the count is correct because I can see it in the debug. I can see something called arg0 in the variables. That has the correct number of characters but I can't use it.
I am still learning and I can't use objects or anything like that for now.
Any help would be appreciated. or if you could point me somewhere I could read. I tried the docs but it was a lot and I got overwhelmed fairly quickly.
You have an error in the inner loop:
for(int j = 0; j >= i; j++)
Note that the outer loop is run for each of the command line argument and the inner loop is run for each character of an argument given by i.
So change it to
for(int j = 0; j < args[i].length(); j++)
for(int j = 0; j < args[i].length(); j++)?
This will sum all uppercases for all strings passed as arguments.
Your code could be simpler if you only expect one string.
To make your code easier to read (and write) you should use foreach loops, one for each string in the args array, and one for each character in the array that we get by doing foo.toCharArray().
The syntax of a foreach loop is as follows:
for (type var : iterable) {
// Code here
}
Where iterable is something with the Iterable interface (usually an array or ArrayList).
We can switch out these in your code and make it a lot easier to read:
String[] args = {"ProgrammingIsFun!", "When It Works..."};
int count = 0;
for (String e : args) {
for (char f : e.toCharArray()) {
if (Character.isUpperCase(f)) {
count++;
}
}
}
System.out.print("The number of upper cases are: " + count);

2D Array Scores

This is the original prompt:
Write program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i = 0;
int j;
while (i < 3) {
j = 0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j] = value;
j++;
}
i++;
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
The part that I need help on is the nested for loop at the bottom of the code. This code is supposed to compute the average of the numbers that are entered; however, I am confused on how to do that with the nested for loop.
you're almost there!
Here are the things you need to do:
1)you've to initialize the variable 'average' after the first for loop.
because average needs to be 0 i.e., reset after second for loop ends each time.
2)you've defined "value = value / scores[i][j]" . I don't know why you did that, but "value = scores[i][j]" must solve your problem.
3) you should print the average only thrice i.e., after calculating average of each row. so, print average at the end of second for loop.
Hope this makes it clear.
here's the code for your reference:
for (i = 0; i < 3; i++) {
int average = 0;
for (j = 0; j < 3; j++) {
value = scores[i][j];
average += value;
}
System.out.println(average/3);
}
Ever i represents a row, every j represents a column.
You need the average of every row, meaning that for every same i and every different j for that i you need to store the values and calculate the average.
Looks like homework code. We can give you hints but not write it for you :(

Loop with incremental value based on user input

I have a task about incremental values in a loop based on user input.
The task is that the following lines are generated in the console
*
**
***
****
*****
And the amount of lines are decided by user input. I.e. if the user types in 2 it gives the following output:
*
**
My current code is:
import static javax.swing.JOptionPane.*;
public class loop1 {
public static void main(String[] args){
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
while (current_line != target_line){
String sign = "*";
System.out.println(sign);
current_line ++;
}
}
}
But I can't seem to get the number of asterisks (*) to increase for every time it runs. How can I accomplish this?
You need a nested loop. Each iteration of the outer loop (which is the loop you already have) would print a single row, and each iteration of the inner loop would print a single asterisk for the current row.
You actually need two loops here, but you only have one. You have a while loop to print out the asterisks, but you also need a loop to increment the number of asterisks printed out each time.
Some pseudocode might look like:
For (int i = 1 to whatever value the user entered):
For (int j = 1 to i):
Print an asterisk
Actual code would look like:
int numLines = Integer.parseInt(showInputDialog("type here "));
for(int numAsterisks = 0; numAsterisks < numLines; numAsterisks++) {
for(int i = 0; i < numAsterisks; i++) {
System.out.print("*");
}
System.out.println(); // Start a new line
}
You can make it simpler by using nested for loops. Modify your loop to:
for (int i=0;i<target_line;i++) {
for (int j=0;j<=i;j++) {
System.out.print("*");
}
System.out.println();
}
You print everytime one '*'-sign.
You don't necessarily need two loops. You can place the sign outside of the loop and you can add an asterisk every iteration with string.concat("*"). Concatenating actually means combining two strings into one, so you actually combine the sign from the previous iteration with a new sign.
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
String sign = "*";
while (current_line != target_line){
sign.concat("*");
System.out.println(sign);
current_line ++;
}

beginner java, showing special characters that correlate to an integer

Doing some homework in my CSC 2310 class and I can't figure out this one problem... it reads:
Write a program that will draw a right triangle of 100 lines in the
following shape: The first line, print 100 '', the second line, 99
'’... the last line, only one '*'. Name the program as
PrintTriangle.java.
My code is pretty much blank because I need to figure out how to make the code see that when i = 100 to print out one hundred asterisks, when i = 99 print ninety-nine, etc. etc. But this is all i have so far:
public class PrintTriangle {
public static void main(String[] args) {
// Print a right triangle made up of *
// starting at 100 and ending with 1
int i = 100;
while (i > 0) {
// code here that reads i's value and prints out an equal value of *
i--;
}
}
}
The rest of the assignment was way more difficult than this one which confuses me that I can't figure this out. Any help would be greatly appreciated.
You clearly need 100 lines as you know. So you need an outer loop that undertakes 100 iterations (as you have). In the body of this loop, you must print i * characters on a single line, so you just need:
for (int j = 0 ; j < i ; j++) System.out.print("*");
System.out.println(); // newline at the end
Hence you will have:
int i = 100;
while (i > 0) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
i--;
}
Or equivalently,
for (int i = 100 ; i > 0 ; i--) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
}
EDIT Using only while loops:
int i = 100; // this is our outer loop control variable
while (i > 0) {
int j = 0; // this is our inner loop control variable
while (j < i) {
System.out.print("*");
j++;
}
System.out.println();
i--;
}
So to break it down:
We have an outer loop that loops from i = 100 downwards to i = 1.
Inside this outer while loop, we have another loop that loops from
0 to i - 1. So, on the first iteration, this would be from 0-99
(100 total iterations), then from 0-98 (99 total iterations), then
from 0-97 (98 total iterations) etc.
Inside this inner loop, we print a * character. But we do this i
times (because it's a loop), so the first time we have 100 *s, then 99, then 98 etc. (as
you can see from the point above).
Hence, the triangle pattern emerges.
You need two loops, one to determine how many characters to print on each line, and an inner nested loop to determine how many times to print a single character.
The hint is that the inner loop doesn't always count to a fixed number, rather it counts from 1 to (100 - something).
Try this:
public class PrintTriangle {
public static void main(String[] args) {
for(int i = 100; i >= 1; i--){
System.out.print("\n");
for(int j = 0; j < i; j++){
System.out.print("*");
}
}
}
}
Explanation: The nested for loop has a variable named j. j is the amount of times * has been printed. After printing it checks if it is equal to i. i is a variable in the big for loop. i keeps track of how many times a line has been printed. \n means newline.
You could come at it side ways...
StringBuilder sb = new StringBuilder(100);
int index = 0;
while (index < 100) {
sb.append("*");
index++;
}
index = 0;
while (index < 100) {
System.out.println(sb);
sb.deleteCharAt(0);
index++;
}
But I think I prefer the loop with loop approach personally ;)
You could improve the effiency of the first loop by increasing the number of stars you add per loop and reducing the number loops accordingly...
ie, add 2 starts, need 50 loops, add 4, need 25, add 5 need 20, add 10, need 10...
For example
while (index < 10) {
sb.append("**********");
index++;
}

Printing out series of numbers in java

hi guys i am just doing some reading for myself to learn java and came across this problem and is currently stuck.
i need to print out series of number based on the input given by the user.
for example, if input = 5, the output should be as follows
#1#22#333#4444#55555
import java.util.*;
public class ex5{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.println("Please type a #: ");
int input = kb.nextInt();
for(int i=0;i<input;i++){
if(input==1){
System.out.print("#1");
}
if(input==2){
System.out.print("#1#22");
}
}
}
}
this doesnt seem to be working because this is the output i get
Please type a #:
2
#1#22#1#22
im not sure what to put inside the for loop right now and i dont think i am using the for loop here very well either...
any help guys?
for (int i=1; i<=5; i++){
System.out.print("#");
for (int j=1; j<=i; j++) System.out.print(i);
}
out
#1#22#333#4444#55555
you're going to need a nested for-loop to solve this problem.
Yeah, this isn't how you want to do it. You're going to want to build the string inside the for loop.
Start with a new string
String s = "";
As you loop, add to that string.
for(int i=1;i<=input;i++){
s += #;
for(int j=0; j<i; j++) {
s+=i;
}
}
You need to use a nested for loop.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Please type a #: ");
int input = kb.nextInt();
for (int i = 1; i <= input; i++) {
System.out.print("#");
for (int k = 0; k < i; k++) {
System.out.print(i);
}
}
}
It is because you are checking for the numbers 1 and 2 in the if statement. It is hard coded to only check for these two numbers and would not work once you go past the values that you have an if statement for
What you want to do is to output the value of your iterator (in your case, i) i times (hint, you can use another loop inside the big loop) and then ad an # sign at the end of the string.
I will try to not give you any code so you can learn it yourself, but feel free to ask more questions.
You are trying to print given number - given number of times?
Then you'll need two loops for this - outer loop for iterating the number and inner - for iterating -times the given number.
It would be something like this:
for(int i = 0; i < input; ++i) {
System.out.print("#");
for(int j = 0; j < i; ++j) {
System.out.print(i);
}
}

Categories