如何将user(int)的输入转换为String

时间:2017-04-04 01:29:46

标签: java java.util.scanner

我编写了这段代码,将用户输入的任何整数转换为星期几。我无法解决我遇到的一些错误,我错过了什么?

 import java.util.Scanner;
   class dayofweek2 {
       public static void main(String[] args) {
         Scanner daynumber = new Scanner(System.in);

         String input = Integer.parseInt(daynumber);
         System.out.println("Enter a number from 1 to 7");
         if (input == 1 ) {
            System.out.println("monday");
         }
         if (input == 2 ) {
            System.out.println("tuesday");
         }
         if (input == 3 ) {
            System.out.println("wednesday");
         }
         if (input == 4 ) {
            System.out.println("thursday");
         }
         if (input == 5 ) {
            System.out.println("friday");
         }
         if (input == 6 ) {
            System.out.println("saturday");
         }
         if (input == 7 ) {
            System.out.println("sunday");
         }
      }
   }

4 个答案:

答案 0 :(得分:2)

代码中有多个杂散/过时的分号。我已为您修复了代码:)

提示:您可以使用switch语句来简化逻辑并使其更具可读性

   import java.util.Scanner;
   class dayofweek2 {
       public static void main(String[] args) {

         Scanner daynumber = new Scanner(System.in); // Print to screen, querying user
         System.out.println("Enter a number from 1 to 7");
         String j = daynumber.nextLine(); // Per requirements, obtain String
         Integer input = Integer.parseInt(j); // Convert String to Integer

         if (input == 1 ) { // Begin processing of input
            System.out.println("monday");
         }
         if (input == 2 ) {
            System.out.println("tuesday");
         }
         if (input == 3 ) {
            System.out.println("wednesday");
         }
         if (input == 4 ) {
            System.out.println("thursday");
         }
         if (input == 5 ) {
            System.out.println("friday");
         }
         if (input == 6 ) {
            System.out.println("saturday");
         }
         if (input == 7 ) {
            System.out.println("sunday");
         }
      }
   }

答案 1 :(得分:1)

你有很多不幸的分号。他们终止了您的if尸体。另外,我会使用Scanner#nextInt()Scanner的不同变量名称。接下来,在尝试阅读input之前显示提示。并且,我将通过使用数组消除所有这些if(s)。像,

Scanner scan = new Scanner(System.in);
System.out.println("Enter a number from 1 to 7");
int input = scan.nextInt();
String[] days = { "monday", "tuesday", "wednesday", "thursday",
        "friday", "saturday", "sunday" };
if (input >= 1 && input <= 7) {
    System.out.println(days[input - 1]);
}

答案 2 :(得分:0)

Scanner需要一些输入。您可以通过调用Scanner.nextLine()或其他next方法之一来完成此操作。

在您的示例中,您可以执行此操作:

Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine(); // read a line
int daynumber = Integer.parseInt(input); // parse the line that was entered as an integer

switch(daynumber) {
    // ...
}

答案 3 :(得分:0)

之后

System.out.println("Enter a number from 1 to 7");

逻辑是grep用户输入的数字并将其存储在变量中。

喜欢

int tmp = daynumber.nextInt();

然后继续使用if或Switch语句