【问题标题】:How to use strings as the same as inputting int?如何像输入int一样使用字符串?
【发布时间】:2018-10-10 18:54:44
【问题描述】:
import java.util.Scanner;
public class DaysInMonth
{
public static void main(String[] args)
  {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter a year:")
  int year = input.nextInt();    enter code here
  System.out.print("Enter a month:"); 
  int month = input.nextInt();    enter code here
  int days = 0;       
  boolean isLeapYear = (year % 4 == 0 && year % 100 != 0)||(year % 400 == 0);       

  switch (month){ 
  case 1: 
  days = 31; 

  break; 
  case 2: 
  if (isLeapYear) 
  days = 29; 
  else 
  days = 28; 

  break; 
  case 3: 
  days = 31; 
  break; 

 case 4: 
 days = 30; 
 break; 

 case 5: 
 days = 31; 
 break; 

 case 6: 
 days = 30; 
 break; 

  case 7: 
  days = 31; 
  break; 

  case 8 
  days = 31; 
  break; 

 case 9: 
 days = 30; 
 break; 

 case 10: 
 days = 31; 
 break; 

 case 11: 
 days = 30; 
 break; 

 case 12: 
 days = 31; 
 break; 
 default: 

String response = "Have a Look at what you've done and try again";
System.out.println(response); 
 System.exit(0); 
} 
  String response = "There are " +days+ " Days in Month "+month+ " of Year "   +year+ ".\n"; 
  System.out.println(response); // new line to show the result to the screen. 
} 

}

如果我输入 1,为什么我不能在一月份输入以获得相同的输出结果?它应该打印“2018 年 1 月有 31 天”我初始化了这个月份,所以它应该是 1 月或任何其他月份。

我知道我有 int 但我想知道如何也使用 January for 1 来获得相同的输出。

【问题讨论】:

  • 使用HashMapInteger 作为键,String 作为值
  • @GBlodgett 或一个数组。
  • 正确缩进您的代码将使其更具可读性,人们将更有可能阅读它。
  • 你想在你的 switch() 中使用一个字符串变量吗?

标签: java switch-statement case


【解决方案1】:

您可以在 switch 语句中使用字符串来检查几种等效情况:

switch (monthInput.toLowerCase()) {
    case "january":
    case "jan":
    case "1":
        days = 31;
        break;

    case "february":
    case "feb":
    case "2":
        days = isLeapYear ? 29 : 28;
        break;

    case "march":
    case "mar":
    case "3":
        days = 31;
        break;

    // etc.

    default:
        System.out.println(monthInput + " is not a valid month");
        input.close();
        System.exit(0);
}

但这意味着您必须将输入读取为String,而不是int...

Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
int year = input.nextInt();     // enter code here
input.nextLine(); // read the rest of the line (if any)

System.out.print("Enter a month:");
String monthInput = input.nextLine();

注意在.nextInt() 之后使用input.nextLine(); — 这是因为nextInt() 调用不会消耗所有输入,它读取您为年份键入的 int ,它确实读取换行符(输入键),因此您必须阅读它才能准备读取 next 输入,即月份编号或名称。

【讨论】:

  • 我会考虑你的建议!
【解决方案2】:

我知道我有 int 但我想知道如何也使用 January for 1 来获得相同的输出。

一个简单的方法是使用名称数组

// before main.
static final String[] MONTH = "?,Jan,Feb,Mar,Apr,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");

// inside main
String monthStr = MONTH[month];

根据需要添加完整的月份名称。

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    相关资源
    最近更新 更多