我在类中定义了一个方法,在该方法中我初始化了一个字符串变量,并使用replaceAll方法初始化了另一个字符串变量,从第一个字符串中删除了元音。如何在主方法中访问第二个字符串同一个班级? 这是我写的代码:
public class removeVowels
{
public static String remV(String y)
{
String str="aebgreiouAfEOHNBI";
String str1=str.replaceAll("[aeiouAEIOU]","");
return str1;
}
public static void main(String[] args)
{
System.out.println(str1);
}
}
答案 0 :(得分:1)
public class removeVowels
{
public static String remV(String y)
{
String stringMinusVowels=y.replaceAll("[aeiouAEIOU]","");
return stringMinusVowels;
}
public static void main(String[] args)
{
String str1 = "Hello";
String str1WithoutVowels = remV(str1);
System.out.println(str1WithoutVowels);
}
}
Soultion:您希望确保您的字符串str1
在您的main方法范围内。这意味着它必须声明:
答案 1 :(得分:0)
根据我对您的问题的理解,看起来您希望将您的变量作为您的类的属性,如下所示:
class removeVowels {
static String str1;
public static String remV(String y) {
String str = "aebgreiouAfEOHNBI";
str1 = str.replaceAll("[aeiouAEIOU]", "");
return str1;
}
public static void main(String[] args) {
System.out.println(str1);
}
}
现在,通过调用remV来获取str1的值可能更有意义
class removeVowels {
public static String remV(String y) {
String str = "aebgreiouAfEOHNBI";
String str1 = str.replaceAll("[aeiouAEIOU]", "");
return str1;
}
public static void main(String[] args) {
System.out.println(remV(""));
}
}
答案 2 :(得分:0)
public class removeVowels
{
static String str1 //declare static string
public static String remV(String y)
{
String str="aebgreiouAfEOHNBI";
str1=str.replaceAll("[aeiouAEIOU]","");
return str1;
}
public static void main(String[] args)
{
remV("write anything"); //function is called so that str1 gets assigned
System.out.println(str1);
}
}