2

I have a class in which there is a method that terminates the program in case a string has the NUL character in it. The particular expression is this:

stringVar.indexOf('\u0000') < 0

This string is read from the user via Scanner and I really wonder how a NUL character may end up in the string through an input from the user.

Edit: Scanner reads the code as follows:

Scanner scannerVar = new Scanner(System.in);
stringVar = scannerVar.next();
Haggra
  • 3,539
  • 2
  • 20
  • 28
  • Please provide the code using the `Scanner` – johnnyaug Aug 14 '16 at 14:29
  • I don't think it would. Is the method working fine? – Codebender Aug 14 '16 at 14:43
  • @Codebender I tried to make it execute the method, that is somehow add a NUL char in the string through user input but I couldn't. But it should be somehow possible otherwise why would the creator of the class add such a method? – Haggra Aug 14 '16 at 14:45
  • @Haggra There is a discussion about null char in the string. Please have a look: http://stackoverflow.com/q/318775/2293534 – SkyWalker Aug 14 '16 at 14:49

1 Answers1

-1

public int indexOf(int ch):

Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur.

You can get blank input using scanner. Link is here: https://stackoverflow.com/a/17504384/2293534

import java.io.*;

public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");
      String SubStr1 = new String("Tutorials");
      String SubStr2 = new String("Sutorials");

      System.out.print("Found Index :" );
      System.out.println( Str.indexOf( SubStr1, 15 ));
      System.out.print("Found Index :" );
      System.out.println(Str.indexOf( SubStr2 ));
   }
}

This produces the following result:

Found Index :-1

Found Index :-1

Resource Link:

Java - String indexOf() Method

Community
  • 1
  • 1
SkyWalker
  • 28,384
  • 14
  • 74
  • 132