search

Home  >  Q&A  >  body text

java - String.indexOf()疑问

先上代码:

package test;

import java.util.Scanner;

public class Char_01 {
    public static final String ENTRY_SPLIT = "" + (char) 1;
    public static final String KEY_VALUE_SPLIT = "" + (char) 2;

    public static void main(String args[]) {
        System.out.println("ENTRY_SPLIT:" + ENTRY_SPLIT + "\nKEY_VALUE_SPLIT:" + KEY_VALUE_SPLIT);
        Scanner scanner = new Scanner(System.in);
        Char_01 _char = new Char_01();
        _char.check(scanner.next());
    }

    public void check(String value) {
        if (-1 != value.indexOf(ENTRY_SPLIT) || -1 != value.indexOf(KEY_VALUE_SPLIT)) {
            throw new IllegalArgumentException("Message的properties不能包含'(char)1' 或 '(char)2'特殊字符");
        }
    }
}

这段代码中的check怎么做到校验特殊字符的?
为什么System.out.println(String.valueOf((char) 1));可以表示特殊字符??还是只是用来校验(char)1和(char)2这两个特殊字符??表示不理解。

ringa_leeringa_lee2767 days ago467

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 17:49:35

    This program only checks the special characters of (char) 1 and (char) 2, which correspond to checking the two characters of ASCII code 01 and 02. The writing is rather strange.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 17:49:35

    You have to look at the ASCII table and you will understand the meaning. This code indicates that when there is a special character with char of 1 or 2, an exception is thrown

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 17:49:35

    The corresponding characters of (char)1(char)2 are as shown below:



    You can paste these two characters into the console and call the check method to trigger an exception.
    -- It seems that the picture cannot be loaded, please post a link to the gallery.
    http://img.junbaor.com/20160428DE215D849D9563AB6BED55BC929D1B7D.png

    reply
    0
  • Cancelreply