涉及字符串和char的switch语句

时间:2015-09-15 14:07:48

标签: java

public class Example {

        public static void main (String [] args){
            String word = "apple";
            switch(word){ // by only changing this value
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
            System.out.println("the word starts with a vowel"); 
            break;
            default:
            System.out.println("the word doesn't start with a vowel");
    }
        }
    }

我所遇到的错误是

 char cannot be converted to a String

如果是这种情况,我应该使用charArray()方法吗?

2 个答案:

答案 0 :(得分:5)

看起来你希望开关盒是单词的第一个字母,而不是整个单词,所以试试这个:

 switch(word.charAt(0)){ // by only changing this value

答案 1 :(得分:3)

你应该尝试获取字符串的第一个元素而不是整个单词。第一个元素应该是Error message: ErrorException (E_WARNING) HELP Callstack information; navigate with mouse or keyboard using Ctrl+↑ or Ctrl+↓ Copy-to-clipboard button Exception message and its type Code snippet where the error was thrown Server state information Application provided context information ErrorException thrown with message "file_put_contents(/services.json): failed to open stream: Permission denied" Stacktrace: #8 ErrorException in /home/project/staging/bootstrap/compiled.php:4000 #7 Illuminate\Exception\Handler:handleError in <#unknown>:0 #6 file_put_contents in /home/project/staging/bootstrap/compiled.php:4000 #5 Illuminate\Filesystem\Filesystem:put in /home/project/staging/bootstrap/compiled.php:4279 #4 Illuminate\Foundation\ProviderRepository:writeManifest in /home/project/staging/bootstrap/compiled.php:4258 #3 Illuminate\Foundation\ProviderRepository:compileManifest in /home/project/staging/bootstrap/compiled.php:4222 #2 Illuminate\Foundation\ProviderRepository:load in /home/project/staging/vendor/laravel/framework/src/Illuminate/Foundation/start.php:210 #1 require in /home/project/staging/bootstrap/start.php:60 #0 require_once in /home/project/staging/public/index.php:35 file_put_contents(/services.json): failed to open stream: Permission denied open: /home/project/staging/bootstrap/compiled.php

char