Programmers learn & share
0 votes
118 views

Problem :

I have written following code so far:

    Scanner scanit = new Scanner(System.in);
    String strscan = scanit.nextLine();
    int x = strscan.length();
    int y = strscan.charAt(x/2);
    System.out.println(strscan.substring(y, x-1));

Because of some reason when I am trying to run above code it is giving me the error.

Please let me know if somebody can help in resolving the issue!

I am very new to java and I only have the basic knowledge in Java. I don't know about the use of arrays and other advanced stuff. If someone can tell me how to resolve this issue in the easiest way possible that would be the great help!

by (7.5k points)   | 118 views

1 Answer

0 votes

Solution :

I know java quite well and so I am helping you in solving your issue.

I have gone through your code and I found that int y = str.charAt(x/2); this line of code is not required. I think you need to return just half the string from the beginning of string.

To achieve the solution please use below code.

public static void main(String[] args) {
Scanner scanit = new Scanner(System.in);
String strscan = scanit.nextLine();
int x = strscan.length();
System.out.println(strscan.substring(0, x/2)); // returns part of full string starting from index 0 to mid index
}

Output

WooHoo

Woo

by (36.1k points)  
2,227 questions
2,734 answers
59 comments
241 users