【发布时间】:2017-09-07 15:31:40
【问题描述】:
我是 Java 新手。我正在努力做我的功课。在此,我首先制作了 StringBuffer 对象 strB1 和 strB2。在接受用户输入后。我创建了一个新的 StringBuffer 对象并将 strB1 的内容复制到该对象。我正在对包含 strB1 内容的新字符串缓冲区对象 strobj 进行所有修改。但是新对象的变化反映在原始对象中。请帮忙。我无法理解为什么要更改原始对象。
您将在代码末尾看到打印两个对象产生相同的结果,而我只对一个对象进行更改。
import java.util.Scanner;
public class Homwork1_Q2 {
StringBuffer strobj2;
Homwork1_Q2()
{
}
// Copy constructor used in part 2 and 3 or hw
Homwork1_Q2(StringBuffer strobj_2)
{
this.strobj2 = strobj_2;
}
public static void main(String args[])
{
// create two StringBuffer objects
StringBuffer strB1 = new StringBuffer();
StringBuffer strB2 = new StringBuffer();
//1. create a obj of Scanner and take input in STRB1
Scanner scan = new Scanner(System.in);
System.out.println("Input the Long String");
strB1.append(scan.nextLine());
//Input a shorter String
System.out.println("Input the Short String");
strB2.append(scan.nextLine());
//If 2nd stringBuffer is longer the first through an
//exception and again take the input
try
{
if(strB1.length() < strB2.length())
{
throw new Exception();
}
}catch(Exception e)
{
System.out.println("2nd String should be shorter.. Input again");
strB2.append(scan.nextLine());
}
// 2. Create a StringBuffer object from the long String
StringBuffer strobj = new StringBuffer();
strobj = strobj.append(strB1.toString());
//3. Using the StringBuffer with the appropriate specific constructor.
Homwork1_Q2 object = new Homwork1_Q2(strB1);
//4. Position of the small string in the long string
//If more then one position is present then it will calculate that too
int position;
int check = 0;
while((strobj.indexOf(strB2.toString()))!=(strobj.lastIndexOf(strB2.toString())))
{
position = strobj.indexOf(strB2.toString());
System.out.println("Small String is present at position "+ (position+check));
strobj.delete(position, position+strB2.length());
check = check+strB2.length();
}
position = strobj.indexOf(strB2.toString());
System.out.println("Small String is present at position "+(position+check));
strobj = strB1;
//5. Delete the small string
//If more then one time small string is present in large string then it will delete them too
while((strobj.indexOf(strB2.toString()))!=(strobj.lastIndexOf(strB2.toString())))
{
position = strobj.indexOf(strB2.toString());
strobj.delete(position, position+strB2.length());
check = check+strB2.length();
}
position = strobj.indexOf(strB2.toString());
strobj.delete(position, position+strB2.length());
check = check+strB2.length();
System.out.println(strobj.toString());
System.out.println(strB1.toString());
}
}
【问题讨论】:
-
您在代码中执行
strobj = strB1;。这将strobj和strB1设置为相同的引用。这是故意的吗? -
没有。那不是故意的。我想将 strB1 的内容复制到 strobj。谢谢你解决了问题。
-
你能告诉我如何将一个StrB1的内容复制到Strobj吗?
-
请不要使用文本输出的截图。
-
顺便说一下,
StringBuffer已经过时了。十三年前,你应该改用StringBuilder。
标签: java stringbuffer