【问题标题】:Why can I not input into a string variable? [duplicate]为什么我不能输入字符串变量? [复制]
【发布时间】:2021-02-10 05:13:29
【问题描述】:

我对 java 很陌生,在高中学习它的课程,我们刚开始使用简单的程序来熟悉语法,但由于某种原因,我无法使用 Scanner 将字符串输入字符串变量。这行代码只是被忽略了。我试过直接复制/粘贴他给我们的老师的笔记,即使在我的电脑上运行,它们也可以在他自己的程序中运行良好,但它们在我的程序中不起作用。我做错了什么?

import java.util.Scanner;
public class Control5
{
    public static void main (String [] args)
    {
        Scanner input = new Scanner(System.in);
        String job;
        System.out.println("1");
        int years;
        System.out.print("How many years have you been employed here? ");
        years = input.nextInt();
        System.out.print("Enter your job title: ");
        job = input.nextLine();
        if ((years > 5) & (job.toLowerCase() == "salesman")) {
            System.out.println("Eligible for promotion.");
        }
        else {
            System.out.println("Not eligible for promotion.");
        }
    }
}

【问题讨论】:

    标签: java input syntax


    【解决方案1】:

    检查它们 1 文件名必须是你的类名(现在必须是 Control5.java)

    2public static void main ( String [] args) 不正确,正确的是 public static void main ( String[] args) 表示 [] 必须放入一个数据类型中,该数据类型表示所有变量都是 String 类型的数组(多个 var 的总和)(java 中的搜索数组)

    3 if((years > 5)&(job.toLowerCase() == "salesman"))

    & 是按位 AND 运算符,比较 AND 运算符是 &&(但两者都有效)

    【讨论】:

    • public static void main (String [] args) 完全正确。我不会在 String 和 [] 之间放置额外的空格,但这对于 Java 语法无关紧要。在告诉所有人它错了之前,您是否尝试过编译它?
    【解决方案2】:

    以下示例应该可以解决您的问题。始终关闭您的输入和输出流示例:input.close()。考虑使用 equals() 或 compareTo() 进行字符串比较。

    public static void main (String[] args) {
             
             // Input stream
             Scanner input = new Scanner(System.in);
             
             // Request User Input and assign corresponding variables the entered value(s)
             System.out.print("How many years have you been employed here? ");
             int years = input.nextInt();
             System.out.print("Enter your job title: ");
             String job = input.next();
             
             // Determine if user is eligible for promotion 
             if (years > 5 && job.toLowerCase().equals("salesman")) {
                System.out.println("Eligible for promotion.");
             }
             else { System.out.println("Not eligible for promotion."); }
             
             // Close input
             input.close();
    }
    

    【讨论】:

    • 我建议你显示 try-with-resources 语法来自动关闭资源。
    • 我为这个年轻人保持简单。他可能还没有学会这一点。我想自从他使用扫描仪以来,他至少已经学会了如何以最基本的方式关闭扫描仪。
    【解决方案3】:

    对不起,我的英语不好。 方法 nextInt 只接收 int 值,它不会读取或跳过 Integer 之后的任何内容。 假设您在控制台“123/n”中输入,方法 nextInt 检索 123 并将其留在缓冲区 /n 中,然后方法 nextLine 检索 /n。因此,不满足条件。

    我们可以使用方法 next 代替 nextLine 或 在方法 nextInt 之前使用方法 nextLine 或 年 = Integer.parseInt(input.nextLine());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-29
      • 2016-12-30
      • 2014-10-07
      • 1970-01-01
      • 2021-05-03
      • 2014-09-30
      • 2021-05-09
      • 2018-10-18
      相关资源
      最近更新 更多