【问题标题】:New to coding, keep getting incompatible errors编码新手,不断收到不兼容的错误
【发布时间】:2016-05-12 16:41:14
【问题描述】:

这是我的代码,这是我的错误信息:

Malcolm.java:9: error: incompatible types: Scanner cannot be converted to int
        age = number;
              ^
Malcolm.java:16: error: incompatible types: possible lossy conversion from double to int
        case .3:
             ^
2 errors

(.3 应该是 3 个月。)

import java.util.Scanner;

class learn {
public static void main (String args[]) {
    Scanner number = new Scanner(System.in); {

    int age;
    System.out.println("Hello Malcolm! Mommy loves you^_^. How old are you  :");
    age = number;


    switch (age) {
    case 0:
        System.out.println("You were born Feb 12 2016 and when you cry you look like an old man");
        break;
    case .3:
        System.out.println("You are 3 months!!! You can smile real big     at mommy and daddy");
        break;
    case 1:
        System.out.println("You will walk");
        break;
    case 2:
        System.out.println("You will talk");
        break;
    case 3:
        System.out.println("You will run and play");
        break;
    default:
        System.out.println("I don't know how old you are. You must be and old man^-^");
        break;
    }
    }
    }


}

【问题讨论】:

    标签: java int switch-statement double


    【解决方案1】:
      age = number;
    

    您正在尝试将扫描仪对象分配给无效的整数。

    你可能想这样做

      age = number.nextInt();
    

    正如@andreas 所说,另一个错误是关于

      case .3:
    

    你不能在 switch 中给出双精度值。您可能需要一些特殊条件。大小写必须是整数。

    【讨论】:

    • 半个答案。另一半:.3 不是 int 值。
    • 如果ageint 而你使用nextInt(),那么.3 甚至是不可能的,所以你的建议是无关紧要的。
    【解决方案2】:

    第一:

    年龄是int,号码是Scanner,你不能这样做

    age = number;
    

    但是

    age = number.nextInt();
    

    第二:

    在你的开关中,你不能混合类型,所以case: .3在这里是不可能的! ageint.3float,所以...不是 int

    因为你不能让float 输入开关,而你的age 不是整数,

    使用 if/else 方法并使用

    double age = number.nextDouble() 
    

    或将您的年龄转换为String,以保持您的开关和使用:

    String age = number.nextLine()
    

    【讨论】:

    • 如果ageint 而你使用nextInt(),那么.3 甚至是不可能的,所以使用if/else 没有任何帮助。我确实喜欢使用String 的建议,因为您可以在上面使用switch
    • 谢谢我决定去掉 .3 并使用 age = number.nextInt();。我知道如何使用 if/else 方法,所以我将创建第二个程序,使用 if/else 来合并 .3 并看看它是如何进行的。我感谢所有的帮助^_^
    • 我也编辑为使用.3,您需要使用double。但是对于double,您需要不要忘记纯integer.0 (3.0, 3.3)
    【解决方案3】:

    编辑:使用嵌套 switch() 添加了第二个版本,见下文。这只是另一种处理年份和月份与总月份的方式。

    其他答案已经解释了扫描仪的情况。 我想给你一些关于如何进行的建议和 对 Java 有足够的了解,这样您就可以继续学习更多。

    处理用户键盘输入可能很复杂,您只需要了解很多就可以做好。 当您刚刚学习 Java 时,这是一个困难的地方。 你不知道你还不知道什么,而且非常不清楚 为什么事情不起作用。 我希望修改后的源代码(如下)能给你一些想法。

    编程愉快:-)

    样本输出

    以下是一些示例输出。
    我认为您将从中受益 并让它做你想做的一切。
    你写了一个很好的学习程序,从这里继续 - 祝你好运。
    逻辑还不是 100%,例如:look to see 如果用户输入“0.2”与“0.3”会发生什么

    $ javac learn.java
    $ java learn
    Hello Malcolm! Mommy loves you^_^. How old are you  :
    input=""
    input has 0 characters.
    expected 1 or more characters, please try again.
    $ java learn
    Hello Malcolm! Mommy loves you^_^. How old are you  :
    0
    input="0"
    input has 1 characters.
    periodLocation=-1
    expected a perid between AGE and MONTHS, please try again.
    $ java learn
    Hello Malcolm! Mommy loves you^_^. How old are you  :
    0.0
    input="0.0"
    input has 3 characters.
    periodLocation=1
    agePart="0"
    monthsPart="0"
    age=0, months=0
    totalMonths=0
    === switch-style ===
    You were born Feb 12 2016 and when you cry you look like an old man
    === if-style ===
    You were born Feb 12 2016 and when you cry you look like an old man
    $ java learn
    Hello Malcolm! Mommy loves you^_^. How old are you  :
    0.2
    input="0.2"
    input has 3 characters.
    periodLocation=1
    agePart="0"
    monthsPart="2"
    age=0, months=2
    totalMonths=2
    === switch-style ===
    I don't know how old you are. You must be and old man^-^
    === if-style ===
    $ java learn
    Hello Malcolm! Mommy loves you^_^. How old are you  :
    0.3
    input="0.3"
    input has 3 characters.
    periodLocation=1
    agePart="0"
    monthsPart="3"
    age=0, months=3
    totalMonths=3
    === switch-style ===
    You are 3 months!!! You can smile real big     at mommy and daddy
    === if-style ===
    You are 3 months!!! You can smile real big     at mommy and daddy
    
    $ java learn
    Hello Malcolm! Mommy loves you^_^. How old are you  :
    2.0
    input="2.0"
    input has 3 characters.
    periodLocation=1
    agePart="2"
    monthsPart="0"
    age=2, months=0
    totalMonths=24
    === switch-style ===
    You will talk
    === if-style ===
    You will talk
    $ java learn
    Hello Malcolm! Mommy loves you^_^. How old are you  :
    2.1
    input="2.1"
    input has 3 characters.
    periodLocation=1
    agePart="2"
    monthsPart="1"
    age=2, months=1
    totalMonths=25
    === switch-style ===
    I don't know how old you are. You must be and old man^-^
    === if-style ===
    You will talk
    $ 
    

    learn.java

    这里是“learn.java”的源代码。 (约定:我鼓励您将下一个类大写,可能像“Learn2.java”或“LearningPartTwo.java”。java 编译器并没有真正 小心,大多数人都会把事情大写)。

    import java.util.Scanner;
    
    class learn {
       public static void main (String args[]) {
       // Handling user input is difficult, for Java you will need to know
       // about Strings, integers, maybe floating point, maybe dates...
       // If the use is directly typing something we will be getting characters,
       // and Java generally handles characters with a String.
       // What you do with the characters your user typed can be challenging...
       // How would you let your user type in....
       //     an age?
       //     an amount of money?  (does currency matter?  yuan? yen? dollars? pounds? )
       //     a fraction?  1/5,  1/3, etc?
       //     text? (like a name) ?
       //     a date?  January 1, 2017
       // I suppose we should start with the basics. :-)
       // All user input from the keyboard will come in as characters.
       // "Scanner" tries to help you by changing those characters into 
       // other Java types.  Until you actually Know those types
       // prett well, I suggest it will be better for you to work direclty
        // with the characters.
       // Then Scanner will be a fine tool and you will understand what it
       // is doing on your behalf.
    
       System.out.println("Hello Malcolm! Mommy loves you^_^. How old are you  :");
       // we're going to move age & months down below.
       // OLD: int age;
       // OLD: int months;
       // Style-wise, as others have pointed out, "Scanner" isn't really a number.
       // So let's change that to just "s" (short for Scanner).
       // OLD: Scanner number = new Scanner(System.in);
       // OLD: age = number;
       Scanner s = new Scanner(System.in);
       String input = s.nextLine(); // ask our scanner for all the characters our user typed.
       // (there are other ways we could get input from our user,
       // but we'll stick with Scanner.)
    
    
       // At this point, whatever our user typed is in the "input" String variable.
       // Never hesitate to add plenty of prints to show what is going on.
       // This helps a lot with debugging and research, you can comment them out
       // when it is working the way you want.
       System.out.println("input=\""+input+"\""); // for debugging, to help you see what is happening.
       System.out.println("input has "+input.length()+" characters."); // for debugging
    
    
       // A major part of handling user intput is validation.
       // We have to make sure they typed what we are looking for.
       // What happens if they just hit enter?
       // What happens if they typed a random word, like "BLUE", instead of an age?
       // What happens if they typed a random word instead of an age?
       // How do we tell if they actually typed in an age?
       // It looks like you want age to be "YEARS.MONTHS"
       // Ok... that is going to be very confusing to people that use periods for decimal separators,
       // like 3.14159  but what the heck - this is just a learning exercise.
    
       // So let's add some validation checks.
       // There are other friendlier ways you could handle problems with the input.
       // If you have studied looping, think about asking the user for a line of input
       // until we get a String we can use as an age.
       // System.exit() is kind of harsh, but just think of it as a stepping stone.
       if( input.length() == 0 ) {
          System.err.println("expected 1 or more characters, please try again.");
          System.exit(0);
       }
    
       int periodLocation = input.indexOf( '.' ); // see if we have a period
       System.out.println("periodLocation="+periodLocation);
       // Question: how would you change this to make "months" optional?
       if( periodLocation == -1 ) {
          System.err.println("expected a perid between AGE and MONTHS, please try again.");
          System.exit(0);
       }
    
       String agePart = input.substring( 0, periodLocation );  // grab everything before the period
       System.out.println("agePart=\""+agePart+"\""); // for debugging
    
       String monthsPart = input.substring( periodLocation+1 );  // grab everything after the perid
       System.out.println("monthsPart=\""+monthsPart+"\""); // for debugging
    
       int age = Integer.parseInt(agePart);
       int months = Integer.parseInt(monthsPart);
    
       // If we were being thorough...
       // a) We might check to make sure we have positive numbers.
       // (What happens if our user types in "-1.-2" ? )
       // b) We would check to make sure we had only digit characters
       // with a single period inside of them.
       // c) What would happen if the users entered more than 12 months, like "0.100"?
       // Would that case problems?
       //
       // The take home lesson here is there are MANY ways for users to give you
       // incorrect input. :-)
       // Anyway, lets see if we have some Java integers now...
    
       System.out.println("age="+age+", months="+months); // for debugging
    
    
       // Good, looks like the integer extract stuff works.
       // Next you want to work with the "3 months" part,
       // which is fractional years, e.g. 0 years and 3 months is 0.25 years.
       // As others have pointed out, switches like integers.
       // So we *could* do a trick like this and talk in terms of months, not years...
    
       int totalMonths = age*12 + months;
       System.out.println( "totalMonths="+totalMonths );
    
        //OLD: switch (age)
       System.out.println("=== switch-style ===");
       switch ( totalMonths ) {
              //OLD: case 0: 
              case 0: 
                 System.out.println("You were born Feb 12 2016 and when you cry you look like an old man");
                 break;
              //OLD: case .3:
              case 3:
                 System.out.println("You are 3 months!!! You can smile real big     at mommy and daddy");
                 break;
              //OLD: case 1:
              case 1*12:
              System.out.println("You will walk");
                 break;
              //OLD: case 2:
              case 2*12:
                 System.out.println("You will talk");
                 break;
              //OLD: case 3
              case 3*12:
                 // note about 1*12, 2*12, 3*12: you could do the math and use 36 here instead of
                 // letting the java compiler handle it, but I think 3*12 is more clear for "intent"
                 // than just 36.
                 System.out.println("You will run and play");
                 break;
              default:
              System.out.println("I don't know how old you are. You must be and old man^-^");
                 break;
                 // kind of a do-nothing break since this is last item in our switch(), but harmless.
           }
    
           // Let's compare the switch{...}  approach to if/else logic.
           // one way to do it is like this...
           // I'll let you decide which approach feels better... much of the "art" of
           // programming is about aesthetics and feel.  People call that "elegance", or
           // lack thereof. :-)  But seriously, it will help you to think of ways to make
           // your code elegant.  And when you're reviewing answers on StackOverflow, check
           // to see which ones get more votes - they tend to be more elegant.
           System.out.println("=== if-style ===");
           if( age == 0 ) {
              if( months == 0 ) {
                 System.out.println("You were born Feb 12 2016 and when you cry you look like an old man");
              } else if( months == 3 ) {
                 System.out.println("You are 3 months!!! You can smile real big     at mommy and daddy");
              }
           } else if ( age == 1 ) {
              System.out.println("You will walk");
           } else if ( age == 2 ) {
                 System.out.println("You will talk");
           } else if ( age == 3 ) {
                 System.out.println("You will run and play");
           } else {
              System.out.println("I don't know how old you are. You must be and old man^-^");
           }
        }
        // That is all I have for you.
        // So, welcome to programming and I hope you have fun learning Java. :-)
        // (p.s. after you learn Java, don't stop - there are more elegant languages out there).
    }
    

    Learn2.java

    我添加了这个以显示嵌套开关,这可能更有意义。嵌套开关使用 age,然后直接使用 months。你的原始程序(上面的learn.java)只有一个开关;为了使单个开关同时适用于 agemonths,我创建了 totalMonths。正如您在 cmets 中指出的那样,我可以理解这令人困惑……希望这更有意义。

    import java.util.Scanner;
    // NEW: see nested switches, below.
    class Learn2 {
       public static void main (String args[]) {
          System.out.println("Hello Malcolm! Mommy loves you^_^. How old are you  :");
          Scanner s = new Scanner(System.in);
          String input = s.nextLine();
          System.out.println("input=\""+input+"\"");
          System.out.println("input has "+input.length()+" characters.");
    
          if( input.length() == 0 ) {
             System.err.println("expected 1 or more characters, please try again.");
             System.exit(0);
          }
    
          int periodLocation = input.indexOf( '.' ); // see if we have a period
          System.out.println("periodLocation="+periodLocation);
          if( periodLocation == -1 ) {
             System.err.println("expected a perid between AGE and MONTHS, please try again.");
             System.exit(0);
          }
    
          String agePart = input.substring( 0, periodLocation );  // grab everything before the period
          System.out.println("agePart=\""+agePart+"\"");
          String monthsPart = input.substring( periodLocation+1 );  // grab everything after the perid
          System.out.println("monthsPart=\""+monthsPart+"\"");
    
          int age = Integer.parseInt(agePart);
          int months = Integer.parseInt(monthsPart);
          System.out.println("age="+age+", months="+months);
    
          switch ( age ) {
             case 0:
                // NEW: a nested switch() { } might be an easier
                // way to handle months than jamming everything
                // into totlaMonths.
                switch( months ) {
                   case 0:
                      System.out.println("You were born Feb 12 2016 and when you cry you look like an old man");
                      break;
                   case 3:
                      System.out.println("You are 3 months!!! You can smile real big     at mommy and daddy");
                      break;
                   default:
                      System.out.println("hit default on switch for months, age="+age+" months="+months );
                } // END for switch( months )
                break; // remember this applies to switch(age), we're no longer in switch(months) at this point.
             case 1:
                System.out.println("You will walk");
                break;
             case 2:
                System.out.println("You will talk");
                break;
             case 3:
                System.out.println("You will run and play");
                break;
             default:
                System.out.println("I don't know how old you are. You must be and old man^-^   (age="+age+", months="+months+")");
                // break; // after case (or default) break doesn't matter.
          }
       }
    }
    

    【讨论】:

    • 感谢大家的回复和示例代码。这对我学习 Java 有很大帮助。如果有人想知道我一直在使用 Treehouse 和 Bucky 的 newboston youtube 帐户来学习。
    • 我对这两行的语法和含义感到困惑: int totalMonths = age*12 + months; System.out.println("age="+age+", months="+months);
    • "totalMonths" 是一种让单个 switch(){ .....} 处理年份和月份值的解决方法。 (打印只是为了调试,所以你可以看到程序中那个时候的变量是什么。)我同意这很令人困惑,但我希望数学足够清楚:例如3年零4个月(随机选择一个例子)是totalMonths = 12 * 3 + 4 = 36 + 4 = 40。嗯......顺便说一句,使用单开关实际上可能不是一个好主意,我正在努力使原始作品保持原样。请参阅修订版(将很快编辑)。
    • 好的,我将添加程序的第二个版本添加到答案中 - 这个不使用 totalMonths。
    【解决方案4】:

    我想这是我第一次回答一个实际问题!当你有很多人帮助解决问题时,学习编码有时很困难,但很容易弄清楚!首先,我对您的代码做了一些更改。这是修改后的全部源码。

        import java.util.Scanner;
    
    class learn {
    public static void main (String args[]) {
        Scanner number = new Scanner(System.in); 
    
        int age;
        System.out.println("Hello Malcolm! Mommy loves you^_^. How old are you  :");
        age = number.nextInt();
    
    
        switch (age) {
        case 0:
            System.out.println("You were born Feb 12 2016 and when you cry you look like an old man");
            break;
     //   case .3:
     //       System.out.println("You are 3 months!!! You can smile real big     at mommy and daddy");
     //       break;
        case 1:
            System.out.println("You will walk");
            break;
        case 2:
            System.out.println("You will talk");
            break;
        case 3:
            System.out.println("You will run and play");
            break;
        default:
            System.out.println("I don't know how old you are. You must be and old man^-^");
            break;
        }
        }
    
    
    }
    

    这里的主要变化如下。

    Scanner number = new Scanner(System.in);
    

    我看到了一个不必要的括号,老实说不需要在那里。所以我删除了那个sn-p代码末尾的括号。

    第二:

         //   case .3:
     //       System.out.println("You are 3 months!!! You can smile real big     at mommy and daddy");
     //       break;
    

    我注释掉了这个 case 语句,因为 double 不是 switch 语句中的一个选项......感觉 int age 是一个整数而不是一个 double,int 不可能存储一个十进制数而不抛出一个错误你的方法。但是,您会注意到,如果您将age 更改为double,您将收到一个关于 switch 如何不能保存双变量以及什么不能保存的新错误。也就是说,如果您真的想要 .3 作为选项,您将需要一个 If-Else 语句来查看该双精度并根据该语句做出回复,而不是使用开关。

    第三,我将age = number; 更改为正确的语句,该语句将接受用户输入并将其存储到您标记为age 的整数变量中

    age = number.nextInt();
    

    这将采用您接下来输入的任何数字并“尝试”将其存储在年龄中。显然,如果您尝试输入十进制数,您将遇到问题。

    最后我删除了你最后的右括号,因为我删除了Scanner number = new Scanner(System.in);末尾的左括号

    我希望这会有所帮助!随着您了解的越来越多,请随时提出更多问题!

    【讨论】:

      猜你喜欢
      • 2013-05-20
      • 2014-05-19
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多