从星期几开始

时间:2018-06-09 12:57:55

标签: java localdate

我的程序有问题,我必须插入一个随机日期(dd / MM / yyyy),如果当天是星期五或星期六,它应该打印出“现在是派对的时间”。我在星期五或星期四插入日期,但它仍然打印出“你应该学习”。有人可以帮忙吗?

Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    LocalDate date = LocalDate.parse(input, formatter);
    System.out.println(date.getDayOfWeek().name());

    if (date.getDayOfWeek().equals("FRIDAY")) {
        System.out.println("Time for party, because it is: " + date.getDayOfWeek());
    }
    else if (date.getDayOfWeek().equals("SATURDAY"))
        System.out.println("Time for party, because it is: " + date.getDayOfWeek());
    else {
        System.out.println("You should study! It is: " + date.getDayOfWeek());
    }

3 个答案:

答案 0 :(得分:3)

LocalDate.getDayOfWeek返回DayOfWeek类型的枚举。但是你要将String与枚举进行比较。

你必须

date.getDayOfWeek() == DayOfWeek.FRIDAY

答案 1 :(得分:1)

您正在将DayOfWeek实例与String实例进行比较,因此它们永远不会相同,因为它们是不同的类型。

一种解决方案是在调用equals:

之前调用toString
if (date.getDayOfWeek().toString().equals("FRIDAY")){...}

或更好地使用:

if (date.getDayOfWeek() == DayOfWeek.FRIDAY) {...}

答案 2 :(得分:1)

您应该将字符串值替换为枚举类型 DayOfWeek.FRIDAY DayOfWeek.SATURDAY 。在将字符串与枚举进行比较时。

import pandas as pd
import numpy as np

# Creating a dataframe and saving as test.csv in current directory
df = pd.DataFrame(np.random.randn(100000, 3), columns=list('ABC'))
df.to_csv('test.csv', index = False)

# Reading in test.csv and saving as test.xlsx

df_new = pd.read_csv('test.csv')
writer = pd.ExcelWriter('test.xlsx')
df_new.to_excel(writer, index = False)
writer.save()