新编码,不断出现不兼容的错误

时间:2016-05-12 16:41:15

标签: java int switch-statement double

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

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;
    }
    }
    }


}

4 个答案:

答案 0 :(得分:1)

  age = number;

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

您可能想要

  age = number.nextInt();

正如@andreas评论的另一个错误是关于

  case .3:

你不能在开关中给出双倍值。您可能想要一些特殊条件。 case必须是整数。

答案 1 :(得分:1)

第一:

年龄为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()

答案 2 :(得分:0)

我想这是我对实际问题的第一次回复!学习编码有时很难,但很容易弄明白,当你有很多人帮助回答问题时!首先,我对您的代码进行了一些更改。这是改变后的全部来源。

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

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

第二

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

我对这个case语句进行了注释,因为double不是switch语句中的一个选项...... Sense int age是一个整数而不是double,没有任何方法int会存储一个十进制数而不抛出一个错误你的方式。但是,您会注意到,如果将age更改为double,您将收到有关切换无法保存双变量的新错误。这就是说你需要有一个If-Else语句才能看到那个double并根据它做出回复,而不是使用一个开关,如果你真的真的想要.3作为一个选项。

第三,我将age = number;更改为正确的语句,该语句将用户输入并将其存储到标记为age

的整数变量中
age = number.nextInt();

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

最后,当我移除Scanner number = new Scanner(System.in);

末尾的开口支架时,我移除了末尾的右括号。

我希望这有帮助!随着您的学习越来越多,请随意提出更多问题!!

答案 3 :(得分:0)

编辑:使用嵌套开关()添加第二个版本,见下面的结尾。这只是处理岁月的另一种方式。几个月与totalMonths。

其他答案解释了Scanner的情况。 我想给你一些关于如何进行的建议 充分了解Java,以便您可以继续学习。

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

快乐的节目: - )

样本输出

以下是一些示例输出。 我认为你会从中受益 并使它做你想做的一切。 你写了一个很好的学习计划,继续从这里开始 - 祝你好运。
逻辑不是100%,例如:看看 如果用户输入“0.2”vs“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

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

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