编辑:使用嵌套 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)只有一个开关;为了使单个开关同时适用于 age 和 months,我创建了 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.
}
}
}