![](/img/trans.png)
[英]How do I search for a String in an array of Strings using binarySearch or another method?
[英]How do I pass an array of strings into another method?
我的代码是这样的:
public class Test() {
String [] ArrayA = new String [5]
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0])
}
}
我尝试了各种方法(无双关语),但没有任何效果。 感谢您的任何帮助!
public class Test {
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
public Test(){ // Your Constructor
method1(arrayA[0]); // Calling the Method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
在您的主类中,您可以仅调用new Test();
或者,如果您希望通过创建Test实例从主类中调用该方法,则可以编写:
public class Test {
public Test(){ // Your Constructor
// method1(arrayA[0]); // Calling the Method // Commenting the method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
在主类,在你创建测试实例main
类。
Test test = new Test();
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
test.method1(arrayA[0]); // Calling the method
并调用您的方法。
编辑:
提示:有一个编码标准,规定永远不要以大写形式启动method
和variable
。
另外,声明类不需要()
。
尝试这个
private void Test(){
String[] arrayTest = new String[4];
ArrayA(arrayTest[0]);
}
private void ArrayA(String a){
//do whatever with array here
}
如果我们正在谈论传递数组,为什么不那么整洁并使用varargs :)您可以传递单个String,多个String或String []。
// All 3 of the following work!
method1("myText");
method1("myText","more of my text?", "keep going!");
method1(ArrayA);
public void method1(String... myArray){
System.out.println("The first element is " + myArray[0]);
System.out.printl("The entire list of arguments is");
for (String s: myArray){
System.out.println(s);
}
}
试试这个片段:
public class Test {
void somemethod()
{
String [] ArrayA = new String [5] ;
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1 (String[] A) {
System.out.println("Here's where I need ArrayA[0]"+A[0]);
}
public static void main(String[] args) {
new Test().somemethod();
}
}
类名不应该具有Test()
我不确定您要做什么。 如果它是Java代码(看起来像),那么如果您不使用匿名类,则在语法上是错误的。
如果这是构造函数调用,则下面的代码:
public class Test1() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0]);
}
}
应该这样写:
public class Test{
public Test() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1(String[] ArrayA){
System.out.println("Here's where I need " + ArrayA[0]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.