Check number of character from command line - java

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);

Related

Rewrite code with two loops and two output statements

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
}

Why is everything after the space not printed?

I created a simple program using the acm library that takes a user inputted string and prints it out in morse. This is the program:
import acm.program.*;
public class morse extends Program{
public void run(){
String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
String word = readLine("Give the word(s) to transcribe: ").toUpperCase();
println("Morse: ");
int j = 0;
for(int i = 0; i < word.length(); i++){
int k = 0;
boolean flag = true;
if(Character.toString(word.charAt(j)).equals(" ")){
println();
}else {
while(!Character.toString(word.charAt(j)).equals(alphabet[k])){
if(k < 25){
k += 1;
}else{
println("Letter was not found.");
flag = false;
break;
}
}
if(flag){
println(morse[k] + " ");
}
j += 1;
}
}
}
}
However, every time the string contains a space, everything after the space is not printed. I seriously cant find the reason behind this. Can anyone help me or even point me somewhere ? Thanks
(The letters after the space are all printed as spaces)
I do not know why you define i in the for loop but never use it. Your main problem is that when you encounter an space you do not increment j. I think you have two options:
increment j after you call println(); inside the if
drop j completely and simply use i wherever j previously was used (probably the better idea)
General recommendation for your code: You are performing too much weird Character and String logic. You could do
drop the alphabet
get the char from the String the same way you currently do
subtract 'A' from it
use the resulting char as index to access the morse array
drop k and the entire while loop.

Printing Simple Patterns in Java

Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}

How do I print out an hourglass using asterisks?

For a homework assignment, I am trying to construct a program that prints an hourglass shape to the screen using asterisks and spaces. I have written the program below, but its output doesn't look anything like an hourglass. Can anyone help me understand why my program isn't producing the expected output?
public class hourglass {
public static void main(String[] args) {
int x = Integer.parseInt(args[0]);
int k = 2 * x - 1;
int c = k;
for (int j = x; j > 0; j--) {
for (int f = j; f <= k; f++) {
System.out.print("*");
}
for (int o = 1; o <= c; o++) {
if (k % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT: I redid the program now it just prints into infinity and beyond, I understand the logic that I need to take in a x number and then run a for loop, each and every time I go through it I -1 from the x.
Can anyone help me with this please? I'm simply trying to deepen my understanding in Java.
public class hourglass
{
public static void main(String[] args)
{
int valueIn = Integer.parseInt(args[0]);
int maxVALUE = 2*valueIn ;
for( int i = 0 ; (valueIn - 1) > i; i--)
{for( int j =1 ; j < maxVALUE; i++)
{
System.out.print("*");}
for (int o = 1; o < maxVALUE; o++) {
if (maxVALUE % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT 2*
If anyone sees this well, here I go.
I've constructed a code on my own for the past 8 hours and now I'm stuck, I don't know how I can "reverse" my for loop to make it print into the other direction here's my code, I don't know what to do and if anyone can give me any insight on how to do this I would be very pleased, I tried doing an if case if(i == 0) but that never happens and I even tried making that if case ==1; but then the loop ran forever.
Any pointers on how to finish my program?
public class mathrandom
{
public static void main ( String [] args)
{
int valueIn = Integer.parseInt(args[0]);
for ( int i = valueIn; 1 <= i; i--){
for ( int k = i ; k < 2*valueIn -1; k++)
{System.out.print(" ");}
{for ( int j = 1; j <= (i*2)-1; j++)
{
System.out. print("*");
}
System.out.println();
}
}
}}
If you don't think in code (and what novice does?), you can try starting by writing a prose(-ish) description of how your program will go about its task, and then writing code that matches up to the prose. For example, you might start with:
Given an input x representing the width of an hourglass shape, print the hourglass to the screen as a series of lines containing asterisks and spaces. The number of asterisks on each line will start at x, count down by two per line until a line containing fewer than two asterisks, then count back up by two per line until it reaches x again. An appropriate number of leading spaces will be printed on each line to center that line's run of asterisks relative to the other lines' (assuming spaces are displayed with the same width as asterisks).
You can even put that into your source code as a comment. In fact, it can help to break it up into several smaller comments, so that you can follow each logical thought with code that corresponds specifically to that thought. If you do that, then not only does it help you organize your code, but you end up with a nicely-documented program without any extra effort.
If you compare my prose to your program, you should see both similarities and differences. Your program performs some kind of count-down, at each step printing zero or more space characters, some asterisks, and then a newline to end the line. Those are basically the right things for it to do, but the details are wrong. Enough wrong and oddly enough wrong, in fact, that I'm inclined to suspect that the program is more cribbed from external sources than thoughtfully constructed de novo. I suggest from here out you devote your attention to writing the program yourself. In fact, consider starting by tossing out everything in main() except int x = Integer.parseInt(args[0]);.

Using nested for loops

I have a specification as below:
Write a program that prints out all the permutations of two numbers that add up to 7. Hint: you can use two nested for loops.
I have done this but I know this is not correct. What numbers should I put in?
public class NestedFor {
public static void main(String[] args) {
for(int i=1; i<=3; i++) {
for(int j=1; j<=i; j++) {
System.out.println(i+ " " +j);
}
}
}
}
Try this (I am assuming you want non-negative numbers, otherwise you have infinite possibilities):
for(int i=0; i<=7, i++)
{
System.out.println(i + "+" + (7-i));
}
No need for two for loops.
If instead of non-negative you require positive numbers, this would become:
for(int i=1; i<7, i++)
{
System.out.println(i + "+" + (7-i));
}
You are almost there. Here are the things that you need to consider:
Assuming that the numbers are required to be positive, the outer loop should go from 1 to 6, inclusive, not from 1 to 3.
Numbers do not need to be in order. Hence, you should not stop the inner loop at i, also going from 1 to 6, inclusive
You need to add an if check before printing i and j.
Once you fix the three things above, your program should work. Good luck!
Your loops should both loop between 1 and 7. Then inside the last for loop you need to check if the sum of i and j equals 7. If it does, print those two numbers.
You really don't need a nested loop.
for (ii = 0; ii<8; ii++) {
System.out.printf("(%d, %d)\n",ii,7-ii);
}
Keep it simple.
I know the "hint" said you could use two nested loops; but in my experience a little bit of cleverness should not be ignored. When your problem gets much larger, being O(n) rather than O(N^2) is a huge difference...
Try this:
for(int i=0;i<7;i++){ //First Loop
for(int j=7;j>0;j--){//Send loop
if((i+j)==7) System.out.println(i+" , "+j); //Permutations printed to terminal
}
}
I guess it's self explaining, two loops going towards each other. Run it and see the lovely result ;)
In mathematics, the notion of permutation relates to the act of permuting (rearranging) objects or values.
A couple of adjustments: I'm taking the liberty of posting a solution but please make sure you understand it!
for (int i = 0; i <= 7/*Need to consider all numbers from 0 to 7*/ ; ++i) {
for (int j = 0; j <= i /*Don't overoptimise: this is good enough and will not generate duplicates*/; j++) {
if (i + j == 7){
System.out.println(i+ "," +j);
}
}
}
It's not the fastest way; spend some time optimising once you have a solution.
public class NestedFor {
public static void main(String[] args) {
for(int i=1; i<=7; i++) {
for(int j=1; j<i; j++) {
if (i + j == 7 ) {
System.out.println(i+ " " +j);
}
}
}
}
}
Check if they add up to 7
if (i+j == 7)
{
//then they add to 7
}
They should both be between 1 and 7 though if you want all numbers between 1 and 7 that add up to 7. If you want to include 0 then start there.
for (int i=1; i<=7; i++)
...and you may want to exclude duplicates
for(int i=1; i<=7; i++) {
for(int j=i; j<=7; j++) { //starts at i, not 1
/* Only check j against numbers equal to or lower than itself
/* to avoid duplicates
*/
}
}
Additionally
Class names should start with a capitol letter, by convention, and in camel case (each word in a phrase has capitol letters
NestedFor

Categories