题目:求1-100的质数:
package com.jishiti;
class demo8 {
public static void main(String[] args) {
int index = 0;
for (int j = 2; j <= 100; j++) {
boolean b = false;
for (int j2 = 2; j2 <j; j2++) {
if (j % j2 == 0) {
b = true;
break ;
} else{
b=false;
}
}
if(b==false){
System.out.println(j);
index++;
}
}
System.out.println("质素有q" + index + "个");
}
}
*键盘录入一个字符串,计算出有几个字符,算出每个字符出现的次数,并按照值字典顺序排序
*
*分析:
*1.键盘录入需要Scanner
*2.统计字符串中每个字符的次数,先要获取字符串中的每个字符,需要将其转化为字符数组
*3.创建hashMap集合,用来存储字符(键)和次数(值),如果集合中存在这个键就值+1,否则值为1
*4.创建treeMap集合(treeSet集合也可以),遍历这时hashMap集合中的元素,将hashMap值作为treeMap的键存储
*5.由于需要降序排列,需要对treeMap传入的比较器的Compare方法进行重写
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HashMap<Character, Integer> hm = new HashMap<>();
TreeMap<Integer, Character> tm = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
int num = i2 - i1;
return num == 0 ? 1 : num;
}
});
System.out.println("请录入一个字符串:");
String str = sc.nextLine();
char[] arr = str.toCharArray();
for (char c : arr) {
hm.put(c, !hm.containsKey(c) ? 1 : hm.get(c) + 1);
}
for (Entry<Character, Integer> en : hm.entrySet()) {
System.out.println(en.getKey() + "=" + en.getValue());
tm.put(en.getValue(), en.getKey());
}
System.out.println(tm);
}
}
//面试题,去除含有abc的元素
package com.work1;
import java.util.ArrayList;
import java.util.ListIterator;
public class mianshiti1 {
public static void main(String[] args) {
ArrayList<String> al= new ArrayList<>();
al.add("aac");
al.add("ac");
al.add("aac");
al.add("acabc");
al.add("c");
al.add("aacc");
String s="abc";
ListIterator<String> li =al.listIterator();
while(li.hasNext()){
if(li.next().contains(s)){
li.remove();
}
}
System.out.println(al);
}
}
/*求1-10的和
11-20的和
21-30的和
.
.
.
91-100的和
*/
package com.work1;
public class mianshiti2 {
public static void main(String[] args) {
int sum=0;
int sum1=0;
for (int i = 1; i <= 100; i++) {
sum+=i;
if (i%10!=0) {
System.out.print(i+"+");
}else {
System.out.println(i+"="+sum);
sum1+=sum;
sum=0;
}
}
System.out.println("sum1="+sum1);
}
}
//七的倍数和数字有七的数过滤掉
package com.work1;
public class mianshiti3 {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if(i%7==0||(""+i).contains("7")){
System.out.print("过,");
}else {
System.out.print(i+",");
}
}
}
} |
|