Question

I was writing a java program that had a switch in a for loop, and the switch wouldn't loop. the code read as follows:

import static java.lang.System.out;
import java.util.Scanner;

public class Translate {


    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String input=null;
        int i;
        char letter;
            do{             
                out.print("Enter a word to translate");
                input=keyboard.next();
            } while(input==null);
            out.println(" ");//blank line, aesthetics.
            for (i=0;i==input.length();i++);//the misbehaving loop{
                letter=input.charAt(i);
                switch(letter){
                case 'a':{
                    out.print("(-)");
                    break;
                }case 'b':{ 
                    out.print("(-|)");
                    break;
                }case 'c':{
                    out.print("(-\\)");
                    break;
                }case 'd':{
                    out.print("(|--)");
                    break;
                }case 'e':{
                    out.print("(|||)");
                    break;
                }case 'f':{
                    out.print("(|-)");
                    break;
                }default:{
                    out.print("GOODBYE");
                }
            }
        }
       }
 }
Was it helpful?

Solution

there are 2 mistakes in this

for (i=0;i==input.length();i++);//the misbehaving loop{
  1. i==input.length() should be i<input.length()
  2. there should not be ; after for loop

for (i=0;i==input.length();i++); should be for (i=0;i<input.length();i++)

OTHER TIPS

The loop is misbehaving because the switch statement is not the part of the for loop. The loop is terminating right where it is declared. This is because of the ; next to the for-loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top