简体   繁体   English

如何在Java中使用StringBuffer接受用户输入?

[英]How to take user input using StringBuffer in java?

I tried this code but its not working 我尝试了此代码,但无法正常工作

import java.util.*;
class StringBuffer
{
    public static void main(String[] args)
    {
        StringBuffer Name1=new StringBuffer();
        Scanner in=new Scanner(System.in);
        System.out.println("Enter a string: ");
        Name1.append(in.nextLine());
        System.out.println(Name1);
    }
}

If the StringBuffer is per-defined then its works. 如果StringBuffer是按定义的,则它可以工作。 But it fails to take input from user. 但是它无法接受用户的输入。

your code is correct but the class name is wrong. 您的代码正确,但类名错误。 change your class name and run it. 更改您的班级名称并运行它。

You are using class StringBuffer which is already a built-in class in Java. 您正在使用class StringBuffer已经是Java中的内置类。
Ref: Oracle doc 参考: Oracle文档

When you instantiate an object like StringBuffer Name1=new StringBuffer(); 当您实例化诸如StringBuffer Name1=new StringBuffer(); within your custom defined class StringBuffer , then it creates an object with reference to your custom defined class StringBuffer . 在您的自定义定义的类StringBuffer ,然后它会参考您的自定义定义的类StringBuffer创建一个对象。

You need to create an object of Java's inbuilt StringBuffer class . 您需要创建Java内置StringBuffer class的对象。

Change your class name to something else or use StringBuilder which is not thread safe but faster than StringBuffer. 改变你的类名到别的或使用StringBuilder的它不是线程安全的,但不是StringBuffer的速度更快。

Additionally, using Scanner class to read your input. 此外,使用Scanner类读取您的输入。
How can I read input from the console using the Scanner class in Java? 如何使用Java中的Scanner类从控制台读取输入?

StringBuffer is a predefined class in java.lang package which you are trying to use but as the name of your class clashes with it, it uses your class definition instead of the predefined one. StringBuffer是您尝试使用的java.lang包中的预定义类,但是当类名与之冲突时,它使用类定义而不是预定义类。

Here Name1.append(in.nextLine()); 此处Name1.append(in.nextLine()); you are calling append method which is not implemented by your class hence will raise an error cannot find symbol . 您正在调用未由您的类实现的append方法,因此将引发错误, cannot find symbol Change your class name to something unique and you are good to go. 将您的班级名称更改为唯一的名称,您就可以开始了。 Nothing wrong with the input. 输入没有问题。

no need to change your class name wheather it's StringBuffer or not. 无需更改类名,无论是否为StringBuffer。 But do one change in your class. 但是,请在您的班级中进行一次更改。 Surely it'll take input from user side 当然,它将接受用户方的输入

public class StringBuffer {

    public static void main(String[] args) {
        java.lang.StringBuffer Name1 = new java.lang.StringBuffer();
        Scanner in=new Scanner(System.in);
        System.out.println("Enter a string: ");
        Name1.append(in.nextLine());
        System.out.println(Name1);
    }
}

It will solve your problem. 它将解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM