Home  >  Article  >  Java  >  Use java to determine the position where a character first appears

Use java to determine the position where a character first appears

王林
王林forward
2021-01-15 10:22:543042browse

Use java to determine the position where a character first appears

Purpose:

(Learning video sharing: java video tutorial)

Use java to determine the position where a character first appears

The implementation code is as follows:

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s  = sc.nextLine();
		String[] a = { "a", "e", "i", "o", "u" };
		List<Integer> list = new LinkedList<Integer>();
		
		int i;
		boolean flag = false;
		for (i = 0; i < a.length; i++) {
			if (s.indexOf(a[i]) != -1) {//s.indexOf(" ")返回元素的下标
				list.add(s.indexOf(a[i]) + 1);
				flag = true;
			}
		}
		if (flag == false) {
			System.out.println("0");
		} else {
			Collections.sort(list);//要返回元音字母首次出现的位置,所以先排序
			System.out.print(list.get(0));//在输出第一个元素就可以
		}
		sc.close();
	}
}

The most important thing is

1. Use List collection List list = new LinkedList()

2. Be sure to use s.indexof() Methods!

3. Collections.sort(list) Sort the collection

Related recommendations: java introductory tutorial

The above is the detailed content of Use java to determine the position where a character first appears. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete