如何使扫描仪读取我的布尔结果?

时间:2018-11-17 18:16:54

标签: java

我正在编写一个带有大量布尔值true或false语句的程序,我希望布尔值的输出能够被扫描程序读取,并希望将其作为某种输出,是否可以做到?

例如:

program NAME
  implicit none
  real :: i, j(i)

  do i=1, 100
    j(i)=2*i
    write(*,*) i , j(i)
  end do
pause
end program

我几乎要求用户输入一个数字,它将转换为实际月份的名称,并通过转换数字来告诉他们生日,但是当我这样做时,它只是将其打印出来。我想让Scanner首先读取输入1,并希望其写为“您的生日是1月1日”

2 个答案:

答案 0 :(得分:0)

您可以使用switch语句并根据输入的数字设置响应字符串,然后在打印语句中使用它。

String response;

switch(day){
  case 1: response = "first";
    break;
  case 2: response = "second";
    break;
  /*
  And so on...
  */
}

答案 1 :(得分:0)

尝试这种方法:

public static void main(String[] args) {
    final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    Scanner sc = new Scanner(System.in);
    System.out.println("Type month: ");

    int month = 0;
    while(sc.hasNextInt()) {
        month = sc.nextInt();
        // get month from 1 to 12
        if (month > 0 && month < 12) {
            break;
        } else {
            System.out.println("Type valid month: ");
            continue;
        }
    }

    System.out.println("Type day: ");
    while (sc.hasNextInt()) {
        int day = sc.nextInt();
        int numDays = 0;
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31; break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30; break;
            case 2: numDays = 28; break;
        }
        // get day taking under consideration amount of days in the month
        if (day > 0 && day <= numDays) {
            System.out.println("Your birthday is " + day + " " + months[month-1]);
            return;
        } else {
            System.out.println("Type valid day: ");
            continue;
        }
    }
}