Chronicle of a newbie programmer. The plan is to start with Java and move into some C++.
Monday, October 19, 2015
StringColumnWords
import java.util.Scanner;
public class Practice_7_2
{
public static void main(String[] args)
{
//declare variables
char ch;
int end, num = 1;
//do while loop allows user to go again
do
{
//prompt user and get input string
System.out.print("Enter a string: ");
Scanner input = new Scanner(System.in);
String sentence = input.nextLine();
//prints title for first word
System.out.print("Word #1:\t");
//for loop runs for length of string
for (int i = 0; i < sentence.length(); i++)
{
//ch is a character in the string
ch = sentence.charAt(i);
//if statement prints letters untiil there is white space
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
System.out.print(ch);
}
else
{
//increments the word number and prints word
num++;
System.out.print("\nWord #" + num + ":\t");
}
}
//asks user if they want to go again and ends if 0 is typed
System.out.print("\nDo you want to go again? ");
end = input.nextInt();
//resets word number to 1
num = 1;
}
while (end != 0);
}
}
http://math.hws.edu/eck/cs124/javanotes4/c3/ex-3-4-answer.html
This post helped me somewhat, although I didn't want to use the character method because we have not covered that in class yet and I would like to be able to solve each problem with the knowledge introduced so far.
This program has a problem if there is any punctuation, so I need to figure out how commas and periods could be covered in the if statement simply.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment