I have to have the user input an integer, then by reading a file I have to find how many times that integer occurs and then the longest sequence of numbers. I think I generally have the method to find these two things but I don't think that I'm reading from the file quite right. I'm using eclipse so does my file have to be in a certain place for it to be read or is my code just completely wrong?
import java.util.Scanner;
import java.io.File;
int[]data;
int []counter;
int temp;
random.data = new int[5000];
try{
random.readDataFromFile();
}
catch(Exception e){
}
random.findInteger();
random.longSequence();
}
//method to receive the input from the user and prints the number of times that the value occurs
public void readDataFromFile() throws Exception {
java.io.File infile = new java.io.File("5000RandomNumbers.txt");
Scanner input = new Scanner(infile);
for (int i = 0; i < data.length; i++) {
data[i] = input.nextInt();
}
input.close();
}
public void findInteger(){
Scanner input = new Scanner (System.in);
//ask user for an integer
System.out.println("Please enter an integer value");
for (int i = 0; i < data.length; i++){
data[i] = input.nextInt();
}
input.close();
for (int i = 0; i < data.length; i++){
temp = data[i];
counter[temp]++;
}
for (int i = 0; i <counter.length; i++){
if (counter[i] > 0 && counter[i]==1){
System.out.println(i + "occurs" + counter[i] + "times");
}
else if (counter[i]>= 2){
System.out.println(i + "occurs" + counter[i] + "times");
}
}
}
//method that prints out the longest increasing sequence in the data
public void longSequence(){
int count = 1;
int max = 1;
for (int i = 1; i < data.length; i++){
if (data[i] >= data[i-1]){
count ++;
}
else{
count = 1;
}
if (count > max){
max = count;
}
}
System.out.println(max);
}
}
You can try using a HashMap
HashMap hmap = new HashMap();
hmap.put(key, value);
You would have your key as the int that you are checking for and the value as the counter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.