It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I'm having trouble getting this program to work, can someone take a look at it and give me a clue on what to do? Thanks!
Design and implement an application that reads a string from the user, then determines and prints how many of each lowercase vowel (a, e, i, o, and u) appear in the entire string . Have a separate counter for each vowel. Also count and print the number of nonvowel characters .
SPECIFICATION OF PROMPTS, LABELS AND OUTPUT : Your code should use the prompt "enter string : ". After the input is read, there are six lines of output , each starting with a different label: "a: ", "e: ", "i: ", "o: ", "u: ", "other: " in that order. After each label is the required count.
For example: if "aardvark heebie jeebies" were read in, the output would be:
a: 3
e: 6
i: 2
o: 0
u: 0
other: 12
import java.util.Scanner;
public class VowelAnalyst{
public static void main(String args []){
int a =0, e = 0, x = 0;
int u = 0, o = 0, other = 0;
String text;
Scanner scan = new Scanner(System.in);
System.out.print("enter string: ");
text = scan.nextLine();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c=='a')
a++;
else if( c=='e')
e++;
else if(c=='i')
x++;
else if(c=='o')
o++;
else if (c=='u')
u++;
else
other++;
}
System.out.println("a: " + a + "\n" +
"e: " + e + "\n" +
"i: " + x + "\n" +
"o: " + o + "\n" +
"u: " + u + "\n" +
"other: " + other);
}
}
Your code is correct except for this part:
else if (c != 'a' && 'e' && 'i' && 'o'&& 'u' )
It should be written like this:
else if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u')
You could make the code more clear by turning every if you have, except the first one, into an else if, and the last else if, where you check to see if the character isn't any of the vowels, can be simply an else:
if (c == 'a')
{
a++;
}
else if (c == 'e')
{
e++;
}
else if (c == 'i')
{
x++;
}
else if (c == 'o')
{
o++;
}
else if (c == 'u')
{
u++;
}
else
{
other++;
}
Your sequence of if statements is invalid. A meaningful rendition would be something like
if (c == 'a') a++;
else if (c == 'e') e++;
...
else other ++;
However, an even better choice would be to use a switch statement, like so
switch (c) {
case 'a':
a++;
break;
case 'e':
e++;
break;
case 'o':
o++;
break;
case 'u':
u++;
break;
default:
other++;
break;
}
After fixing that, we need look at what you're missing: all uppercase vowels are currently counted as other. We could double up on the conditionals
if (c == 'a' || c == 'A')
...
or
case 'A':
case 'a':
...
But there's an easier way: convert the string to lowercase before the comparison.
for (int i = 0; i < text.length(); i++) {
char c = Character.toLowerCase(text.charAt(i));
switch (c) {
...
I'll do for each char
switch (c)
{
case 'a':
case 'A':
a++;
break;
case 'e':
case 'E':
e++;
break;
case 'i':
case 'I':
i++;
break;
case 'o':
case 'O':
o++;
break;
case 'u':
case 'U':
u++;
break;
default:
other++;
break;
}
It simply counts every vowel and consonants.
Related
I'm learning Java, and we got a project to make a program translating text into ASCII, and back.
My main method so far is
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char decisionOne;
System.out.println("Are we making a new message or decrypting an old one?");
decisionOne = s.nextLine().charAt(0);
switch(decisionOne) {
case 'd':
decrypt();
System.exit(0);
break;
case 'D':
decrypt();
System.exit(0);
break;
case 'E':
encrypt();
System.exit(0);
break;
case 'e':
encrypt();
System.exit(0);
break;
}
while (!(decisionOne == 'd') && !(decisionOne == 'D') && !(decisionOne == 'e') && !(decisionOne == 'E')) {
System.out.println("Hey! Choose one of them.");
decisionOne = s.nextLine().charAt(0);
switch(decisionOne) {
case 'd':
decrypt();
System.exit(0);
break;
case 'D':
decrypt();
System.exit(0);
break;
case 'E':
encrypt();
System.exit(0);
break;
case 'e':
encrypt();
System.exit(0);
break;
}
}
}
and my method for encrypting into ASCII is
Scanner s = new Scanner(System.in);
System.out.println("What is your message?");
String message = s.nextLine();
char m;
int length = message.length();
int tracker = 0;
int ascii;
while (length >= 0 ) {
m = message.charAt(tracker);
length--;
ascii = (int)m;
System.out.print(ascii + " ");
tracker ++;
}
}
I've looked around at other questions, but none of them seem to answer what's happening here. When I run, I get the right output, so if I entered
11
I would get
49 49 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
What could I do to fix this?
Change your code in encrypt method from while(length >= 0) to while(length - 1 >= 0). Also close the scanner object after using it as it would result in memory leak.
The length() method return the length of the string, (e.g) String message = "Hello"; length = message.length(); length would be equal to 5. But while using it in the while loop you have to use message.length() - 1 because in Java indexing starts at 0 rather than at 1.
I refactored your encypt method and main method and also I feel there is no need to use switch statements. Replace them with if else statements to reduce redundant code.
If you find this solution useful, kindly upvote the solution Thank you.
public static void encrypt() {
Scanner s = new Scanner(System.in);
System.out.println("What is your message?");
String message = s.nextLine();
char m;
int length = message.length();
int tracker = 0;
int ascii;
while (length - 1 >= 0 ) {
m = message.charAt(tracker);
length--;
ascii = (int)m;
System.out.print(ascii + " ");
tracker++;
}
s.close();
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char decisionOne;
System.out.println("Are we making a new message [e (or) E] or decrypting an old one [d (or) D] ?");
decisionOne = s.nextLine().charAt(0);
if (decisionOne == 'd' || decisionOne == 'D') {
decrypt();
System.exit(0);
}
else if (decisionOne == 'e' || decisionOne == 'E') {
encrypt();
System.exit(0);
}
while (!(decisionOne == 'd') && !(decisionOne == 'D') && !(decisionOne == 'e') && !(decisionOne == 'E')) {
System.out.println("Hey! Choose one of them.");
decisionOne = s.nextLine().charAt(0);
if (decisionOne == 'd' || decisionOne == 'D') {
decrypt();
System.exit(0);
}
else if (decisionOne == 'e' || decisionOne == 'E') {
encrypt();
System.exit(0);
}
}
s.close();
}
I put this in your encrypt method and..
m = message.charAt(tracker);
System.out.print(length + " ");
length--;
ascii = (int)m;
System.out.print(ascii + " ");
tracker ++;
System.out.print(length + " "+tracker+" ");
output i got is thisss...
2 49 1 1 1 49 0 2
you see your tracker=2 in the last which is out of bound for your message string that's why you are getting an exception either you can handle the exception or improve your code ...
personal experience -- use for loop if you are a beginner it will give you more clarity on how the code works
You want while (length > 0) or while (tracker < length)
Or you can just do for (Character m: message.toCharArray()) and forego the length, tracker, and charAt method
I made a method in java that prints a menu screen that looks like this:
MENU
c - Number of whitespace characters
f - Find text
r - Replace all !'s
q - Quit
Choose an option:
The method returns a char. How do I use the return value of the method in main to make if else statements?
printMenu method:
public static char printMenu(Scanner scnr) {
char menuOp;
//display the menu
System.out.println("\nMENU");
System.out.println( "c - Number of whitespace characters");
System.out.println("f - Find text");
System.out.println("r - Replace all !\'s");
System.out.println("q - Quit\n");
menuOp = ' ';
//loop until the user has entered a c, f, r or q
while (menuOp != 'c' && menuOp != 'f' &&
menuOp != 'r' &&
menuOp != 'q') {
System.out.println( "Choose an option:");
menuOp = scnr.nextLine().charAt(0);
}
//return the letter that the user entered
return menuOp;
} //end of the printMenu method
What I want to be able to do in main:
while (return value from printMenu method != 'q'){
printMenu(scnr);
if (return value from printMenu method == 'c'){ //do this
}
else if (return value from printMenu method == 'f'){ //do this
}
else if (return value from printMenu method == 'r'){ //do this
}
}
}
I'm still new and really appreciate the help, patience, and kindness. Thanks
Edit - I have to use the return value from printMenu() as a requirement for a project.
This seems like a good example for using a do-while loop:
Scanner scanner = new Scanner(System.in);
char c;
do
{
c = printMenu(scanner);
switch (c)
{
case 'c':
//do something
break;
case 'f':
//do something
break;
case 'r':
//do something
break;
}
} while(c != 'q');
Answered by sweeper:
menuChar = printMenu(scnr);
import java.util.Scanner;
public class lab05a
{
public static void main (String[] args)
{
String statement;
Scanner scan = new Scanner(System.in);
int vowela;
int vowele;
int voweli;
int vowelo;
int vowelu;
int nonvowel;
int vowela = 0;
int vowele = 0;
int voweli = 0;
int vowelo = 0;
int vowelu = 0;
statement = scan.nextString();
statement = statement.toLowerCase();
for (int i = 0; i <= statement.length(); count++)
{
char c = examplestring.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
switch (c)
{
case 'a':
vowela += 1;
break;
case 'e':
vowele += 1;
break;
case 'i';
voweli += 1;
break;
case 'o';
vowelo += 1;
break;
case 'u';
vowelu += 1;
break;
}
else
nonvowel +=1;
}
System.out.prinln("a: " + vowela);
System.out.prinln("e: " + vowele);
System.out.prinln("i: " + voweli);
System.out.prinln("o: " + vowelo);
System.out.prinln("u: " + vowelu);
System.out.prinln("nonvowel: " + novowel);
}
}
I thought of doing it this way:
First I create a for loop to iterate through every character of String statement.
Then I put an if statement in the for loop that checks if c(declared as statement.charAt(i)) is a vowel.
If c is a vowel I use a switch to increase the count for that particular vowel by one and then break.
If c is not a vowel, it gets added to the count of consonants.
After the for loop is done it prints the count of each character.
The switch is where I am having problems. Case 'a' and case 'e' have cause no errors, but cases 'i' through 'u' cause an error('Error: : Expected').
I don't understand what this means or why, as cases 'i' through 'u' are written the same way as cases 'a' and 'e'. Can someone help me out?
3 errors found:
[line: 38] Error: : expected
[line: 41] Error: : expected
[line: 44] Error: : expected
Sorry if this post is poorly formatted I am new to Stack Overflow.
There are many errors in your code, I have modified it (posted at the bottom) and pointed out some of your mistakes:
Change statement = scan.nextString().toLowerCase(); to statement = scan.nextLine().toLowerCase();
I don't understand what this means or why, as cases 'i' through 'u' are written the same way as cases 'a' and 'e'.
Your switch is wrong because cases i, o, and u have a semi-colon(;) instead of a colon(:). Just that small difference is causing the error there. Change your switch statement to this:
switch(c) {
case 'a':
vowela++;
break;
case 'e':
vowele++
break;
case 'i':
voweli++
break;
case 'o':
vowelo++
break;
case 'u':
vowelu++;
break;
}
Here's your modified code. Now it is correct, and it works:
import java.util.Scanner;
public class lab05a {
public static void main (String[] args) {
String statement;
Scanner scan = new Scanner(System.in);
int vowela = 0;
int vowele = 0;
int voweli = 0;
int vowelo = 0;
int vowelu = 0;
int nonvowel = 0;
statement = scan.nextLine().toLowerCase();
for (int i = 0; i < statement.length(); i++) {
char c = statement.charAt(i);
switch (c) {
case 'a':
vowela++;
break;
case 'e':
vowele++;
break;
case 'i':
voweli++;
break;
case 'o':
vowelo++;
break;
case 'u':
vowelu++;
break;
default:
nonvowel++;
break;
}
}
System.out.println("a: " + vowela);
System.out.println("e: " + vowele);
System.out.println("i: " + voweli);
System.out.println("o: " + vowelo);
System.out.println("u: " + vowelu);
System.out.println("nonvowel: " + nonvowel);
}
}
You may have noticed some changes such as removing the if statement that checks for a vowel. Rather than doing all of that, I just added a default case. If none of the other conditions are true, than whatever is in the default case is executed. I also initialized your variables vowela, vowele, voweli, etc., and rather than doing vowela += 1 I just changed it to vowela++, which produces the same effect(same with the other letters).
I'm not sure how to add a line counter because if I do a while statement such as
while (fileReader.hasNextLine()) {
lines+=1;
file.nextLine();
}
then the rest of my vowels, sentences, etc are set to 0.
my code is:
Scanner input = new Scanner(System. in );
System.out.println("Enter file name: ");
File file = new File(input.nextLine());
if (file.length() == 0) {
System.out.println("The input file is empty.");
System.exit(1);
}
Scanner fileReader = new Scanner(file);
while (fileReader.hasNext()) {
String word = fileReader.next();
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels += 1;
if ((ch == '!' || ch == '.' || ch == '?')) sentences += 1;
if (Character.isLetterOrDigit(ch)) alphaNumeric += 1;
switch (ch) {
case ',':
punctuation += 1;
break;
case '[':
punctuation += 1;
break;
case ']':
punctuation += 1;
break;
case ':':
punctuation += 1;
break;
case '`':
punctuation += 1;
break;
case '-':
punctuation += 1;
break;
case '!':
punctuation += 1;
break;
case '_':
punctuation += 1;
break;
case '(':
punctuation += 1;
break;
case ')':
punctuation += 1;
break;
case '.':
punctuation += 1;
break;
case '?':
punctuation += 1;
break;
case '"':
punctuation += 1;
break;
case ';':
punctuation += 1;
break;
}
}
words += 1;
}
System.out.println("The number of words in the file name: " + words);
System.out.println("The number of lines in the file name: " + lines);
System.out.println("The number of alphanumeric characters " + "in the file name: " + alphaNumeric);
System.out.println("The number of sentences in the file name: " + sentences);
System.out.println("The number of vowels in the file name: " + vowels);
System.out.println("The number of punctuations in the file name: " + punctuation);
Newlines are denoted by the character '\n'. You could check for instances of that, the same way you are checking for vowels, punctuation, etc.
Use these set of lines
String line = fileReader.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels += 1;
if ((ch == '!' || ch == '.' || ch == '?')) sentences += 1;
if (Character.isLetterOrDigit(ch)) alphaNumeric += 1;
switch (ch) {
// do something
}
}
lines ++;
words += line.split(" ").length;
In your original code, the words were nothing but lines. They were not words as such.
I am pretty sure, that stacks are used for building PRN and '(' are ignored, but it does not seem to be the case. For example:
input 1: 52+(1+2)*4-3
input 2: 52+((1+2)*4)-3
input 3: (52+1+2)*4-3
Input 1 and input 2 output should be the same, and input 1 and input 3 should differ.
output 1: 52 1 2 + 4 3 - * +
output 2: 52 1 2 + 4 * 3 - +
output 3: 52 1 2 + 4 3 - * +
public static String Infix2(String input) {
char[] in = input.toCharArray();
Stack<Character> stack = new Stack<Character>();
StringBuilder out = new StringBuilder();
for (int i = 0; i < in.length; i++)
switch (in[i]) {
case '+':
case '*':
case '-':
out.append(' ');
stack.push(in[i]);
break;
case ' ':
case '(':
break;
case ')':
out.append(' ');
out.append(stack.pop());
break;
default:
out.append(in[i]);
break;
}
while (!stack.isEmpty()) {
out.append(' ');
out.append(stack.pop());
}
return out.toString();
}
Assuming that i want input 1 and 3 also to work, what approach should i use?
edit:
After the changes '+','-','*' and '/' worked for given inputs.
public static String Infix2(String input) {
if (input == null)
return "";
char[] in = input.toCharArray();
Stack<Character> stack = new Stack<Character>();
StringBuilder out = new StringBuilder();
for (int i = 0; i < in.length; i++)
switch (in[i]) {
case '+':
case '-':
while (!stack.empty()
&& (stack.peek() == '*' || stack.peek() == '/'))
out.append(' ').append(stack.pop());
case '*':
case '/':
out.append(' ');
case '(':
stack.push(in[i]);
case ' ':
break;
case ')':
while (!stack.empty() && stack.peek() != '(')
out.append(' ').append(stack.pop());
if (!stack.empty())
stack.pop();
break;
default:
out.append(in[i]);
break;
}
while (!stack.isEmpty())
out.append(' ').append(stack.pop());
return out.toString();
}
The algorithm is pretty simple (and here is a good explanation). Every operation has a binding weight, with + and - being the lowest. There are two rules:
print out numbers immediately
never put a lighter item on a heavier item
left parentheses go on the stack
right parentheses pop off the stack until you hit a left parentheses, and then remove the left parentheses
Given your first example, 52+(1+2)*4-3, here is the stack:
52+ => +
52+( => + (
52+(1+ => + ( +
52+(1+2) => + //right parentheses popped +
52+(1+2)*4 => + *
52+(1+2)*4-3 => + - //can't put - on top of *, so pop off *
... and then pop the stack until it's empty.
Replacing your switch loop with the following (closest analog to what you had) will give correct answers for your three examples. In a real parser you would give each operator a weight and generalize the pop mechanism.
for (int i = 0; i < in.length; i++)
switch (in[i]) {
case '+':
case '-':
while (!stack.empty() && (stack.peek() == '*' || stack.peek() == '/')) {
out.append(' ');
out.append(stack.pop());
}
out.append(' ');
stack.push(in[i]);
break;
case '*':
case '/':
out.append(' ');
stack.push(in[i]);
break;
case '(':
stack.push(in[i]);
break;
case ')':
while (!stack.empty() && stack.peek() != '(') {
out.append(' ');
out.append(stack.pop());
}
stack.pop();
break;
default:
out.append(in[i]);
break;
}
Not an exact answer to the specific question but something I'd recommend for developing these kinds of algorithms: have a look at test driven devlopment (TDD). In brief: write a couple of unit tests - for example with JUnit - for the infix2 method, where you feed the method with test patterns (expressions) and test, if infix2 produces the right output.
Start with easy ones, like
assertequals("1", "1"); // positive number
assertequals("-1", "-1"); // negative number
assertequals("1+1", "1 1 +"); // simple addition
assertequals(" 1 + 1 ", "1 1 +"); // simple addition with whitechars
assertequals(" 1 + +1 ", "1 -1 +"); // simple addition with pos. number & whitechars
assertequals(" 1 + -1 ", "1 -1 +"); // simple addition with neg. number & whitechars
assertequals("(1+1)", "1 1 +"); // simple addition with brackets
and don't forget illegal expressions like
String[] illegalExpressions = {null, "", " ", "1 +", "1 + 1)"};
The test cases for you examples should be
assertequals("52+(1+2)*4-3", "52 1 2 + 4 * 3 -");
assertequals("52+((1+2)*4)-3", "52 1 2 + 4 * 3 -");
assertequals("(52+1+2)*4-3", "52 1 + 2 + 4 * 3 -");