[英]how do i make a function that will accept a string and return the second character from the string?
For example if the function is given the string "ABCD" the function should return the letter B. This is code i've written so far but i'm getting a few errors which i've been trying to fix for three hours now! 例如,如果给该函数字符串“ ABCD”,则该函数应返回字母B。这是我到目前为止编写的代码,但是我遇到了一些错误,而这些错误我已经尝试修复了三个小时!
import java.util.Scanner;
public class Stringg {
public static void main(String[] args)
{
System.out.print("Please enter a string: ");
mystring = Scanner.nextLine();
public static char getSecondChar(String myString) {
return myString.charAt(1);
}
System.out.println("The second character is " + getSecondChar (myString));
public class SecondChar {
public static char secondChar(String str){
char[] charArray=str.toCharArray();
if(charArray.length<=1)
{
System.out.println("String does not have 2nd character!");
return 0;
}
return charArray[1];
}
public static void main(String a[]){
String str="ABCD";
System.out.println(secondChar(str));
}
}
In java, writing a function inside a function doesn't mean anything. 在Java中,在函数内部编写函数没有任何意义。 You need to write functions in different scopes.
您需要在不同的范围内编写函数。
Try this. 尝试这个。 Do not create your function inside the main method.
不要在main方法内创建函数。 You will only need to call the function inside the main method to work.
您只需调用main方法内部的函数即可工作。
public class Stringg {
public static char getSecondChar(String myString) {
return myString.charAt(1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a string: ");
String mystring = sc.nextLine();
System.out.println("The second character is " + getSecondChar(mystring));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.