Simple string mistake
I am trying to create a string method in java where it prompts someone to enter a string longer than three characters. Once entered, I want to display the middle three characters of that string. Somet开发者_如何学Gohing is wrong because it is not compiling. Can anyone see my mistake? I can't find it. Thanks.
//MyString.java
import java.util.Scanner;
public class MyString .java {
public static void main (String[] args)
{
String string;
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a string with a minimum of three characters: " + string);
string = scan.nextLine();
System.out.println ("You entered: " + string);
String middle3;
System.out.println ("The middle three characters of the string: " + middle3);
}
}
public class MyString .java {
this is wrong. remove ". java"
You are using MyString .java
as the class name. Java does not allow space and period to be part of a valid class name. I guess you meant MyString
.
Also variables string
and middle3
are not initialized before their use.
You are not actually calculating middle3. It isn't even initialized to null. I imagine you want:
String middle3 = (string.length < 3) ? null : string.substring(string.length / 2 - 1), string.length / 2 + 2);
or something like that.
Why do you append string here?
System.out.println ("Enter a string with a minimum of three characters: " + string );
here you should initialize middle
:
String middle3 ="something";
System.out.println ("The middle three characters of the string: " + middle3);
精彩评论