java next( ) 和 next( ).CharAt(0) 的区别;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33582237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:52:35  来源:igfitidea点击:

Difference between next( ) and next( ).CharAt(0);

javastringchar

提问by PSN

I have created an abstract class Employee which displays and calculates the Details of Weekly and Hourly Employee.In the main method i have used switch case for a menu and do while to continue using the program as long as the user want.But I'm getting an Error when compiling the code.:

我创建了一个抽象类 Employee,它显示和计算每周和每小时员工的详细信息。在主要方法中,我使用 switch case 作为菜单,并在用户需要的时候继续使用该程序。但我是编译代码时出现错误。:

*javac "AbstractDemo.java" (in directory: /home/user/Desktop)
AbstractDemo.java:52: error: incompatible types
    ch=s.next();
             ^
  required: char
  found:    String
1 error
Compilation failed.*

This is the Source Code:

这是源代码:

import java.util.*;
abstract class Employee{
    Employee(float amt,int n){
        float sal;
        System.out.println("The amount paid to Employee is:"+amt);
        sal=amt*n;
        System.out.println("Total Salary is:"+sal);
    }

} 
class WeeklyEmployee extends Employee{
        WeeklyEmployee(float a,int n){
        super(a,n);
    }
}
class HourlyEmployee extends Employee{
        HourlyEmployee(float amt,int hrs){
        super(amt,hrs);
    }
}           

public class AbstractDemo {

    public static void main (String args[]) {
        int a;
        char ch;
        float amount;
        int hours;
        int weeks;
        Scanner s=new Scanner(System.in);
        do{

        System.out.println("Enter the choice");
        a=s.nextInt();
        switch (a) {
            case 1 :
        System.out.println("Enter the salary of weekly employee(Per Week):");
        amount=s.nextFloat();
        System.out.println("Enter the total no of week");
        weeks=s.nextInt();
             Employee W=new WeeklyEmployee(amount,weeks);break;
             case 2:

        System.out.println("Enter the salary of hourly employee(Per hour):");
        amount=s.nextFloat();
        System.out.println("Enter the total no of hours");
        hours=s.nextInt();
        Employee H=new HourlyEmployee(amount,hours);break;
            default:System.out.println("Error invalid Choice");
    }
    System.out.println("Do you wish to continue?(Y/N)");
    ch=s.next();
}while (ch== 'y'||ch== 'Y');

}
}

But When i use s.next().ChatAt(0);the code compiles successfully.Could somebody explain why this is happening?Is Char taking input as String?Or if it is a string why its showing an Error when i edit the while condition to while(ch=="y"||ch=="Y");?

但是当我使用s.next().ChatAt(0);代码编译成功时,有人可以解释为什么会发生这种情况吗?Char 是否将输入作为字符串?或者如果它是一个字符串,为什么在我编辑 while 条件时显示错误while(ch=="y"||ch=="Y");

回答by Eran

chis a char. s.next()returns a String. You can't assign a Stringto a char. You can assign the first character of the Stringto a char, which is what you do in ch = s.next().charAt(0);.

ch是一个chars.next()返回一个String. 您不能将 a 分配String给 a char。您可以将 the 的第一个字符分配String给 a char,这就是您在 中所做的ch = s.next().charAt(0);

It's a good thing you are not trying while(ch=="y"||ch=="Y"), since that would fail even if you changed chto be a String(which would allow it to pass compilation, but wouldn't give the expected result), since you can't compare Strings in Java with ==(you should use equalsinstead).

这是一件好事,您没有尝试while(ch=="y"||ch=="Y"),因为即使您更改ch为 a String(这将允许它通过编译,但不会给出预期的结果)也会失败,因为您无法将StringJava 中的 s 与==(你应该equals改用)。

回答by Rehman

s.next()returns the next String object. But s.next().charAt(0)returns the first character of the next String object. Hence its expecting character and throwing error

s.next()返回下一个 String 对象。但s.next().charAt(0)返回下一个 String 对象的第一个字符。因此它的预期特性和抛出错误

回答by Mohammed Aouf Zouag

the method next()of the Scannerobject returns a String. So in order for your assignment to work, you need to extract the first character from this string using the charAt()method.

该方法next()的的Scanner对象返回String。因此,为了让您的作业正常工作,您需要使用该charAt()方法从该字符串中提取第一个字符。

And since ch is a character not String, while(ch == "y" || ch == "Y")won't work.

并且由于 ch 是一个字符而不是字符串,while(ch == "y" || ch == "Y")因此不起作用。

Use while(ch == 'y' || ch == 'Y')instead.

使用while(ch == 'y' || ch == 'Y')来代替。

(single quotes = character, double quotes = string)

(单引号 = 字符,双引号 = 字符串)

回答by Hoang Tran Son

This because chis charand your idea is input single letter Y or N to stop or continue your program. But, you use method next() of Scanner that return a String. That's main reason why you get this

这是因为chchar并且您的想法是输入单个字母 Y 或 N 来停止或继续您的程序。但是,您使用返回字符串的 Scanner 的 next() 方法。这就是你得到这个的主要原因

*javac "AbstractDemo.java" (in directory: /home/user/Desktop) AbstractDemo.java:52: error: incompatible types ch=s.next(); ^ required: char found: String 1 error Compilation failed.*

*javac "AbstractDemo.java" (in directory: /home/user/Desktop) AbstractDemo.java:52: error: incompatible types ch=s.next(); ^ required: char found: String 1 error Compilation failed.*

When you try to use s.next().ChatAt(0). It mean that you try to get first character from input.
-> this is just imcompatible types error when you try to assign String to Char without converting it.

当您尝试使用s.next().ChatAt(0) 时。这意味着您尝试从输入中获取第一个字符。
-> 当您尝试将 String 分配给 Char 而不转换它时,这只是不兼容的类型错误。

回答by Calvin P.

When you use s.next(), it is read as a string. That's why you get an error with ch=s.next()

当您使用 s.next() 时,它被读取为一个字符串。这就是为什么你会收到 ch=s.next() 错误的原因

However, s.next().charAt(0) will return a char value which can be used by your variable.

但是, s.next().charAt(0) 将返回一个 char 值,您的变量可以使用该值。

Likewise, when you compare char ch to 'y', it compares two chars, but "y" reads as a string and would cause a type mismatch.

同样,当您将 char ch 与 'y' 进行比较时,它会比较两个字符,但“y”读取为字符串并会导致类型不匹配。