'Error: Expected' when creating switch - java

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

Related

RPN calculator with additional functions

I want to make the code use the stack class (stack of integers), together with a driver program which can handle the operations: 'm' unary minus -- negate the top item, 'r' exchange the top two items, 'd' duplicate top item on the stack, 'p' print (to the screen) the top item, n print and remove the top item, f print all the contents of the stack (leaving it intact), c clear the stack, 'q' quit, 'h' (or ?) print a help message.
import java.util.Scanner;
public class CalculatorDemo {
public static void main(String[] args)
{
String expression;
int result;
Scanner in = new Scanner(System.in);
do
{
calculator evaluator = new calculator();
System.out.println("Enter a valid post-fix expression one token " +
"at a time with a space between each token (e.g. 5 4 + 3 2 1 - + *)");
System.out.println("Each token must be an integer or an operator (+,-,*,/,%)for help(h/?)");
expression = in.nextLine();
result = evaluator.evaluate(expression);
System.out.println();
System.out.println(result);
}
while (result = 'q');
System.exit(0);
}
}
import java.util.*;
public class calculator
{
private Stack<Integer> stack;
public calculator()
{
stack = new Stack<Integer>();
}
public int evaluate(String expr)
{
int op1, op2, result = 0, help;
String key;
Scanner parser = new Scanner(expr);
while (parser.hasNext())
{
key = parser.next();
if (isOperator(key))
{
op2 = (stack.pop()).intValue();
op1 = (stack.pop()).intValue();
result = evaluateSingleOperator(key.charAt(0), op1, op2);
stack.push (new Integer(result));
}
else
stack.push(new Integer(Integer.parseInt(key)));
}
return result;
}
private boolean isOperator(String key)
{
return ( key.equals("+") || key.equals("-") ||
key.equals("*") || key.equals("/") ||
key.equals("h") || key.equals("?") ||
key.equals("p") || key.equals("n") ||
key.equals("d") || key.equals("r") ||
key.equals("c") || key.equals("f") ||
key.equals("%") || key.equals("m") ||
key.equals("q") );
}
private int evaluateSingleOperator(char operation, int op1, int op2)
{
int result = 0;
switch (operation)
{
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
case 'p':
result = op2;
break;
case '%':
result = op1 % op2;
break;
case 'm':
result = --op1;
break;
case'q':
result = (0);
break;
case'h'|'?':
int help = 0;
result = help;
break;
case 'r':
result = op1 ;//help
break;
case 'd':
result = op1;//help
break;
case 'n':
result = op1;//help
break;
case 'f':
result = op1;//help
break;
case 'c':
result = op1;//help
break;
}
return result;
}
private void help(String string) {
// TODO Auto-generated method stub
System.out.println("+ add the top two items" +
"* multiply the top two items" +
"- subtract the top item from the next item" +
"/ integer divide the second item by the top item" +
"% find the integer remainder when dividing the second item by the top item" +
"m unary minus -- negate the top item" +
"r exchange the top two items" +
"d duplicate top item on stack" +
"p print (to the screen) the top item" +
"n print and remove the top item" +
"f print all the contents of the stack (leaving it intact)" +
"c clear the stack" +
"q quit" +
"h (or ?) print a help message");
}
}

Having trouble counting down and printing loops

So I need my code to print out in increments on 3 user inputs, I have a 2nd java file to use dot notation to execute methods from. So it's supposed to run kinda like this.
Pick > Starting Value - Pick Increment value - Pick > Ending Value
All these are user input and I need to have it if the starting value > then the ending then count up from starting value with user input increments. But if end
import java.util.Scanner;
public class logic {
public static void main(String [] args) {
//new scanner
Scanner input = new Scanner(System.in);
//Data
char ch = 0;
int start = 0;
int end = 0;
int inc = 0;
String printStr = "";
final int SENTINEL = -1;
String menu ="Looping (Demo)" +
"\nStart Value\t [S]" +
"\nIncrement value [I]" +
"\nEnd Value\t [E]" +
"\nFor Looping\t [F]" +
"\nQuit\t\t [Q]" +
"\nEnter Option > ";
while(ch != SENTINEL) {
switch(ch) {
case 'S':
case 's':
start = UtilsDM.readInt("Enter loop start value: ", false);
break;
case 'I':
case 'i':
inc = UtilsDM.readInt("Enter loop increment value: ", false);
break;
case 'E':
case 'e':
end = UtilsDM.readInt("Enter loops end value: ", false);
break;
case 'F':
case 'f':
if(start <= end){
for (int i=start; i<=end; i+=inc) {
System.out.print(i + " ");
}//end loop +
}//end if
else if(start >= end){
for (int i=end; i<=start; i-=inc) {
System.out.print(i + " ");
}//end loop -
}//end else if
System.out.println("\n");
break;
case 'Q':
case 'q':
System.out.println("Terminating upon user command.");
System.exit(0);
break;
default:
System.out.println("Unrecognized character");
break;
}//end switch
ch = UtilsDM.readChar(menu, false);
}//end loop
//computations, algorithms
//outputs, formatting, display
} //end main
}//end class
Change the case 'F' to as follows, i have commented the changes :-
case 'F':
case 'f':
if(start < end || (start < 0 && end < 0 && end > start)) // start < end or start = -3 and end = -7
{
for (int i=start; i<=end; i+=inc)
{
System.out.print(i + " ");
}
}
else if(start > end || (start < 0 && end < 0 && start > end)) // if start = - 7 and end = -3
{
for (int i=end; i>=start; i-=inc) // should be greater than
{
System.out.print(i + " ");
}
}
else if(start == end)
{
System.out.println(end);
}

Switch statement inside for loop does not increment "i" correctly

I have the following code:
String everything = sb.toString(); //stores all the data from the input file into a string
String replaceAll = everything.replaceAll("\\s", "");
int charCount = replaceAll.length(); //charCount is 147
char arr[] = replaceAll.toCharArray();
for (int i = 0; i < arr.length; i++) {
switch (arr[i]) {
case 'E': {
fridge[Character.getNumericValue(arr[(i + 1)])].is_empty();
}
break;
case 'F': {
fridge[Character.getNumericValue(arr[(i + 2)])].find_it(Character.getNumericValue(arr[(i + 1)]));
}
break;
case 'C': {
fridge[Character.getNumericValue(arr[(i + 3)])].combineFridge(fridge[Character.getNumericValue(arr[(i + 2)])], fridge[Character
.getNumericValue(arr[(i + 1)])]);
}
break;
case 'M': {
fridge[Character.getNumericValue(arr[(i + 3)])].commonItems(fridge[Character.getNumericValue(arr[(i + 2)])], fridge[Character
.getNumericValue(arr[(i + 1)])]);
}
break;
case 'I': {
fridge[Character.getNumericValue(arr[(i + 2)])].insertItem(Character.getNumericValue((i + 1)));
}
break;
case 'D': {
fridge[Character.getNumericValue(arr[(i + 2)])].delete_item(Character.getNumericValue((i + 1)));
}
break;
case 'O': {
fridge[Character.getNumericValue(arr[(i + 1)])].outputRefrigerator();
}
break;
}
}
The char array has 147 elements, and there's a number after each letter.
Each letter activates a method, followed by 1-3 parameters (numbers).
However, inside the for loop, I am getting a -1 value and sometimes random large numbers (all my numbers are positive and less than 12).
If I manually call any method outside the for loop for example:
fridge[Character.getNumericValue(arr[0].insertItem(Character.getNumericValue(arr[1]);, everything works fine and the value which is at arr[1] (which is 1) is stored at this.fridgeItems (an int[] array).
Why is this happening? I know it's a problem with either the switch statement or the for loop but I can't really tell.
Check your indices. In your code you are accessing elements from arr by i + 1 and i + 2 index. If your loop iterates more than n - 2 times, you will have IndexOutOfBoundException.
By the way, you need to increment i in your switch statement to skip "used" characters from the input array.
Your code is "not increment i correctly", because there is no code in the switch statement to actually increment i.
You should do something like this:
case 'C':
fridge[Character.getNumericValue(arr[i + 3])]
.combineFridge(fridge[Character.getNumericValue(arr[i + 2])],
fridge[Character.getNumericValue(arr[i + 1])]);
i += 3;
break;

Convert Binary to Hex in Java using loop and switch

public static void main(String[] args) {
Scanner ms = new Scanner(System.in);
String binary = ms.nextLine();
binary=binary.trim();
//add leading zeroes if length divided by 4 has remainder.
while (binary.length() % 4 != 0) binary = "0" + binary;
String number = "";
for (int i = 0; i < binary.length(); i += 4) {
String num = binary.substring(i, i + 3);
switch(num)
{
case "0000" : number = "0"; break;
case "0001" : number = "1"; break;
case "0010" : number = "2"; break;
case "0011" : number = "3"; break;
case "0100" : number = "4"; break;
case "0101" : number = "5"; break;
case "0110" : number = "6"; break;
case "0111" : number = "7"; break;
case "1000" : number = "8"; break;
case "1001" : number = "9"; break;
case "1010" : number = "A"; break;
case "1011" : number = "B"; break;
case "1100" : number = "C"; break;
case "1101" : number = "D"; break;
case "1110" : number = "E"; break;
case "1111" : number = "F"; break;
}
System.out.println(number);
}
}
I need to use loop and a switch op to do the conversion. After making those changes. I get my result of binary 1111 1110 as F then E on the next line. How can I fix that? I don't want to use stringbuilder because I haven't learn that. Is there any other simple code to do that?
Your return statement is inside your for loop, so after the first iteration you will return from the function. Also, you are overwriting number at every itteration. You should instead replace number with a StringBuilder and user append().
public static void main(String[] args) {
Scanner ms = new Scanner(System.in);
String binary = ms.nextLine();
binary.trim();
//add leading zeroes if length divided by 4 has remainder.
while (binary.length() % 4 != 0) binary = "0" + binary;
StringBuilder number = new StringBuilder();
for (int i = 0; i < binary.length(); i += 4) {
String num = binary.substring(i, i + 4);
switch(num)
{
case "0000" : number.append("0"); break;
case "0001" : number.append("1"); break;
case "0010" : number.append("2"); break;
case "0011" : number.append("3"); break;
case "0100" : number.append("4"); break;
case "0101" : number.append("5"); break;
case "0110" : number.append("6"); break;
case "0111" : number.append("7"); break;
case "1000" : number.append("8"); break;
case "1001" : number.append("9"); break;
case "1010" : number.append("A"); break;
case "1011" : number.append("B"); break;
case "1100" : number.append("C"); break;
case "1101" : number.append("D"); break;
case "1110" : number.append("E"); break;
case "1111" : number.append("F"); break;
}
System.out.println(number.toString());
}
return;
}
Also, others have also mentinoed, your binary.trim() does not work as expected, it needs to be binary = binary.trim().
Strings are immutable
binary = binary.trim(); //not just binary.trim();
Also, you'd want to get the string from index 0 to 3, not 0 to 4. So it's (i, i+3)
So in here it should be:
for (int i = 0; i < binary.length(); i += 4) {
String num = binary.substring(i, i + 3);
Also, take out the return statement at the bottom, because it exits the method when you do one iteration
Its because you're returning from the first iteration of the loop.
Anyways, here's the piece of code that does just what you want , convert binary string to hexadecimal
static String binToHex(String binStr){
while(binStr.length() % 4 != 0){
binStr = "0" + binStr;
}
String hexString = "";
binStr = new StringBuilder(binStr).reverse().toString();
for(int index = 0, len = binStr.length(); index < len;){
int num = 0;
for(int indexInQuad = 0; indexInQuad < 4; indexInQuad++, index++){
int bit=Integer.parseInt(String.valueOf(binStr.charAt(index)));
num += (bit * Math.pow(2,indexInQuad));
}
hexString += Integer.toHexString(num).toUpperCase();
}
hexString = new StringBuilder(hexString).reverse().toString();
return hexString;
}
it also saves you the switch statements
just pass it the binary string value and it works seamlessly :D
The immediate problem with your code is that you return right after printing the first number! Remove the return, and it will print the other numbers, too.
Also, as noted by Josh, you have to do binary = binary.trim();, as trim() will not alter the string in-place but return a trimmed version of the string.
And finally, note that you could replace most of your code with just this...
int n = Integer.parseInt(binary, 2);
String s = Integer.toString(n, 16);
System.out.println(s.toUpperCase());

Vowel counting code issues [closed]

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.

Categories