题目:
虚拟机ID,CPU利用率
其文件格式是这样的:(两项中间用逗号分隔)
题目要求:
1. 统计使用最近频繁的虚拟机,以及其最大CPU利用率是多少?
2. 优化实例代码
参考链接:https://blog.youkuaiyun.com/qq_21808961/article/details/78857170
此链接是分割单词,感觉差不多;
建立了两个map对象,因为要统计三个数据,虚拟机id、使用次数、cpu使用率
hashmap<虚拟机id,使用次数>
hashmap1<虚拟机id,cpu使用率>
number表示使用次数,uselv为cpu利用率
因为value值可以覆盖,在算最大cpu利用率时,只要cpu是利用率数值比原来的大,便会存入,最后留下的便是最大cpu利用率了
emmmmm
新手。。代码写得过于啰嗦难懂,好多知识点都是自己推测出来的,最后结果是对的,望谅解,,,,,
package softwaretest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class problem2 {
public static void main(String[] args) throws FileNotFoundException
{
File file=new File("D:\\softwaretest2\\container.txt");
if(!file.exists())
{
System.out.println("文件不存在");
return;
}
Scanner scanner=new Scanner(file);
Scanner scanner1=new Scanner(file);
HashMap<String, Integer > hashMap=new HashMap<String,Integer>();
HashMap<String, Integer > hashMap1=new HashMap<String,Integer>();
System.out.println("原txt文件-----------------------------------");
while(scanner.hasNextLine())
{
String line=scanner.nextLine();
System.out.println(line);
String[] lineWords=line.split(" ");
//String[] lineWords2=line.split(",");
Set<String> wordSet=hashMap.keySet();
for(int i=0;i<lineWords.length;i++)
{
if(lineWords[i].matches("null")){
//System.out.println("该机器名:"+lineWords[i]);
break;
}
String[] lineWords2=lineWords[i].split(",");//每行中需要用逗号分隔成两部分
if(wordSet.contains(lineWords2[0]))
{
Integer number=hashMap.get(lineWords2[0]);
number++;
hashMap.put(lineWords2[0],number);
}
else
{
hashMap.put(lineWords2[0], 1);
}
}
}
//System.out.println("统计使用次数:------------------------------");
Iterator<String> iterator=hashMap.keySet().iterator();
int max=0;
String machine = null;
while(iterator.hasNext())
{
String word=iterator.next();
//System.out.printf("虚拟机:%s 使用次数:%d\n",word,hashMap.get(word));
if(max<hashMap.get(word)){
max=hashMap.get(word);
machine=word;
}
}
//System.out.printf("使用最频繁的虚拟机是:%s 使用次数:%d\n",machine,max);
while(scanner1.hasNextLine())
{
String line1=scanner1.nextLine();
String[] lineWords1=line1.split(" ");//用非单词符来做分割,分割出来的就是一个个单词
Set<String> wordSet1=hashMap1.keySet();
for(int i=0;i<lineWords1.length;i++)
{
if(lineWords1[i].matches("null")){
break;
}
String[] lineWords21=lineWords1[i].split(",");
Integer uselv=Integer.parseInt(lineWords21[1]);
if(wordSet1.contains(lineWords21[0]))
{
Integer before=hashMap1.get(lineWords21[0]);
if(uselv>before){
hashMap1.put(lineWords21[0],uselv);
}
}
else
{
hashMap1.put(lineWords21[0], uselv);
}
}
}
Iterator<String> iterator1=hashMap1.keySet().iterator();
System.out.println("检测结果--------------------------------");
while(iterator1.hasNext())
{
String word1=iterator1.next();
if(word1.matches(machine)){
System.out.printf("虚拟机:%s 使用次数:%d 最大CPU使用率:%d\n",word1,max,hashMap1.get(word1));
}
}
System.out.println("程序结束--------------------------------");
}
}