How to use delimiters to ignore floats greater than 1? - java

So I'm reading in a two column data txt file of the following from:
20 0.15
30 0.10
40 0.05
50 0.20
60 0.10
70 0.10
80 0.30
and I want to put the second column into an array( {0.15,0.10,0.05,0.2,0.1,0.1,0.3}) but I don't know how to parse the floats that are greater than 1. I've tried to read the file in as scanner and use delimiters but I don't know how to get ride of the integer that proceeds the token. Please help me.
here is my code for reference:
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.*;
class OneStandard {
public static void main(String[] args) throws IOException {
Scanner input1 = new Scanner(new File("ClaimProportion.txt"));//reads in claim dataset txt file
Scanner input2 = new Scanner(new File("ClaimProportion.txt"));
Scanner input3 = new Scanner(new File("ClaimProportion.txt"));
//this while loop counts the number of lines in the file
while (input1.hasNextLine()) {
NumClaim++;
input1.nextLine();
}
System.out.println("There are "+NumClaim+" different claim sizes in this dataset.");
int[] ClaimSize = new int[NumClaim];
System.out.println(" ");
System.out.println("The different Claim sizes are:");
//This for loop put the first column into an array
for (int i=0; i<NumClaim;i++){
ClaimSize[i] = input2.nextInt();
System.out.println(ClaimSize[i]);
input2.nextLine();
}
double[] ProportionSize = new double[NumClaim];
//this for loop is trying to put the second column into an array
for(int j=0; j<NumClaim; j++){
input3.skip("20");
ProportionSize[j] = input3.nextDouble();
System.out.println(ProportionSize[j]);
input3.nextLine();
}
}
}

You can use "YourString".split("regex");
Example:
String input = "20 0.15";
String[] items = input.split(" "); // split the string whose delimiter is a " "
float floatNum = Float.parseFloat(items[1]); // get the float column and parse
if (floatNum > 1){
// number is greater than 1
} else {
// number is less than 1
}
Hope this helps.

You only need one Scanner. If you know that each line always contains one int and one double, you can read the numbers directly instead of reading lines.
You also don't need to read the file once to get the number of lines, again to get the numbers etc. - you can do it in one go. If you use ArrayList instead of array, you won't have to specify the size - it will grow as needed.
List<Integer> claimSizes = new ArrayList<>();
List<Double> proportionSizes = new ArrayList<>();
while (scanner.hasNext()) {
claimSizes.add(scanner.nextInt());
proportionSizes.add(scanner.nextDouble());
}
Now number of lines is claimSizes.size() (also proportionSizes.size()). The elements are accessed by claimSizes.get(i) etc.

Related

Print specific number from text file using an ArrayList and scanner

I need to get a specific number out from a text file by typing a number using a scanner.
The program needs to be able to add multiple numbers together.
Example If i type 1 then I would get the number 80. And after I type 2 then I would get the number 85 and then adding the two numbers together. Result 80 + 85 = 165.
My text file looks like this:
1
80
2
85
3
50
I am able to print all the numbers from my text file and getting it in to an ArrayList but I need to get a specific number printed out.
You can Read all the txt file data and stored it into the Map in Key value pair. Key will be Number index and Value will be actual number. Then fetch the keys from map and add their respective values.
Code will look like:
public class NumberRead{
public static String readFileAsString(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main(String[] args) throws Exception {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
String data = readFileAsString("-----Your Numbers.txt Path-----");
String[] split = data.split("\\s+");
for(int i=0;i<split.length;i++) {
if(i%2==0) {
map.put(Integer.parseInt(split[i]), Integer.parseInt(split[i+1]));
}
}
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number Index");
int first = sc.nextInt();
System.out.println("Enter Secound Number Index");
int second = sc.nextInt();
if(map.containsKey(first)&&map.containsKey(second)) {
System.out.println("Addition is: "+((map.get(first))+map.get(second)));
} else {
System.out.println("Indexes are not present");
}
sc.close();
}
}
And your Numbers.txt file should be in following format:
1 80
2 85
3 50
4 95
5 75
Instead of using Array list, use and store it in HashMap(key value pair) in java.
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
map.put(1,80);
map.put(2,85);
// To retrieve the values
map.get(2); // returns 85
So that retrieval of values is easy and complexity O(1).

Reading multiple lines from console in java

I need to get multiple lines of input which will be integers from the console for my class problem. So far I have been using scanner but I have no solution. The input consists of n amount of lines. The input starts with an integer followed by a line of series of integers, this is repeated many times. When the user enters 0 that is when the input stops.
For example
Input:
3
3 2 1
4
4 2 1 3
0
So how can I read this series of lines and possible store each line as a element of an array using a scanner object? So far I have tried:
Scanner scan = new Scanner(System.in);
//while(scan.nextInt() != 0)
int counter = 0;
String[] input = new String[10];
while(scan.nextInt() != 0)
{
input[counter] = scan.nextLine();
counter++;
}
System.out.println(Arrays.toString(input));
You need 2 loops: An outer loop that reads the quantity, and an inner loop that reads that many ints. At the end of both loops you need to readLine().
Scanner scan = new Scanner(System.in);
for (int counter = scan.nextInt(); counter > 0; counter = scan.nextInt()) {
scan.readLine(); // clears the newline from the input buffer after reading "counter"
int[] input = IntStream.generate(scan::nextInt).limit(counter).toArray();
scan.readLine(); // clears the newline from the input buffer after reading the ints
System.out.println(Arrays.toString(input)); // do what you want with the array
}
Here for elegance (IMHO) the inner loop is implemented with a stream.
You could use scan.nextLine() to get each line and then parse out the integers from the line by splitting it on the space character.
As mWhitley said just use String#split to split the input line on the space character
This will keep integers of each line into a List and print it
Scanner scan = new Scanner(System.in);
ArrayList integers = new ArrayList();
while (!scan.nextLine().equals("0")) {
for (String n : scan.nextLine().split(" ")) {
integers.add(Integer.valueOf(n));
}
}
System.out.println((Arrays.toString(integers.toArray())));

How to use a Movie Review file to print out sentiment averages for words in another file?

I am working on a project that has many different parts and methods. For this one specific part I need to ask the user for the name of a file that contains a set of words, one per line. (see attached) Then I need to compute the average score/sentiment of the word by comparing it to a movieReview file that scores the sentiment of words. (see attached)
[Edit] : I have not gotten my code to take the first line of the wordList file, search through the movieReview file for the word, and find the average score of the word. And after the search is complete, move onto the next word. However, it is printing NaN for the rest of the words after the first, "mechanical"
Example: The first word in the wordList file is "mechanical". Mechanical is found in the movieReview file 6 times and the total score is 4. The average sentiment for the word "mechanical" is .666666666.
How can I make my code so the loop continues and finds the average for every single word and prints it out? Sorry if this sound confusing, let me know if I need to clarify. Also, I am a very beginner coder so please try to not use difficult concepts. (Also, it was said using an array or buffer wasn't needed)
Movie Review File :
http://nifty.stanford.edu/2016/manley-urness-movie-review-sentiment/movieReviews.txt
Content of Word List file(txt):
mechanical
car
soulless
style
family
wonderful
historical
nor
strong
slapstick
complicated
provoking
interest
cast
witty
muted
sentiment
narrative
refreshing
preachy
horrible
resolutely
terrible
dialogue
incoherent
spend
words
moving
devoid
indulgent
dull
value
barely
always
dog
tale
hardly
unfocused
formulaic
eccentric
quirky
unpredictable
tears
writing
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class methodThree {
public static void main (String [] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the file with words you want to score: ");
String inputFileName = in.next();
File inputFile = new File(inputFileName);
while(!inputFile.exists())
{
System.out.println("Please enter a valid file name:");
inputFile = new File(in.next());
}
Scanner wordFile = new Scanner (inputFile);
File inputMovie = new File("movieReviews.txt");
Scanner movieReview = new Scanner (inputMovie);
String reviewText;
int reviewScore;
while (wordFile.hasNextLine())
{
int count = 0;
double total = 0;
String word = wordFile.nextLine();
while (movieReview.hasNext()) {
reviewScore = movieReview.nextInt();
reviewText = movieReview.nextLine();
if (reviewText.contains(word)) {
count++;
total = total + reviewScore;
}
}
double average = (total / count);
System.out.println (word + " " + average);
}
}
}
So what you basically want to do is repeat this code for every line in the wordfile?
int count = 0;
double total = 0;
String word = wordFile.nextLine();
while(movieReview.hasNext()){
reviewScore = movieReview.nextInt();
reviewText = movieReview.nextLine();
if (reviewText.contains(word)) {
count++;
total = total + reviewScore;
}
}
double average = (total / count);
System.out.println(average);
if thats the case you could surround it with another while loop. The loop must run for every line in wordFile, so it's more or less the same loop as your movieReview.hasNext() loop.
while(wordFile.hasNext()){
int count = 0;
...
}
The loop runs as long as wordFile has another word to score.

How to break a loop in Java where the input size is not previously specified?

I need to input n numbers, store them in a variable and make them available for later processing.
Constraints:
1. Any number of SPACES between successive inputs.
2. The count of inputs would be UNKNOWN.
3. Input set should not exceed 256KB and should be between 0<= i <=10^18
Example Input:
100
9
81
128
1278
If I understand your question, then yes. One way, is to use a Scanner, and hasNextDouble()
Scanner scan = new Scanner(System.in);
List<Double> al = new ArrayList<>();
while (scan.hasNextDouble()) { // <-- when no more doubles, the loop will stop.
al.add(scan.nextDouble());
}
System.out.println(al);
if you're input is all coming in on one line like in your text, you could do something like:
import java.util.ArrayList;
public class Numbers
{
public static void main(String[] args)
{
ArrayList<Double> numbers = new ArrayList<Double>();
String[] inputs = args[0].split(" ");
for (String input : inputs)
{
numbers.add(Double.parseDouble(input));
}
//do something clever with numbers array list.
}
}

Scanning from a certain, random line of a file in java?

I have a .txt file that lists integers in groups like so:
20,15,10,1,2
7,8,9,22,23
11,12,13,9,14
and I want to read in one of those groups randomly and store the integers of that group into an array. How would I go about doing this? Every group has one line of five integers seperated by commas. The only way I could think of doing this is by incrementing a variable in a while loop that would give me the number of lines and then somehow read from one of those lines that is chosen randomly, but I'm not sure how it would read from only one of those lines randomly. Here's the code that I could come up with to sort of explain what I'm thinking:
int line = 0;
Scanner filescan = new Scanner (new File("Coords.txt"));
while (filescan.hasNextLine())
{
line++;
}
Random r = new Random(line);
Now what do I do to make it scan line r and place all of the integers read on line r into a 1-d array?
There is an old answer in StackOverflow about choosing a line randomly. By using the choose() method you can randomly get any line. I take no credit of the answer. If you like my answer upvote the original answer.
String[] numberLine = choose(new File("Coords.txt")).split(",");
int[] numbers = new int[5];
for(int i = 0; i < 5; i++)
numbers[i] = Integer.parseInt(numberLine[i]);
I'm assuming you know how to parse the line and get the integers out (Integer.parseInt, perhaps with a regular expression). If you're sing a scanner, you can specify that in your constructor.
Keep the contents of each line, and use that:
int line = 0;
Scanner filescan = new Scanner (new File("Coords.txt"));
List<String> content = new ArrayList<String>(); // new
while (filescan.hasNextLine())
{
content.add(filescan.next()); // new
line++;
}
Random r = new Random(line);
String numbers = content.get(r.nextInt(content.size()); // new
// Get numbers out of "numbers"
Read lines one by one from the file, store them in a list and generate a random number from the list's size and use it to get the random line.
public static void main(String[] args) throws Exception {
List<String> aList = new ArrayList<String>();
Scanner filescan = new Scanner(new File("Coords.txt"));
while (filescan.hasNextLine()) {
String nxtLn = filescan.nextLine();
//there can be empty lines in your file, ignore them
if (!nxtLn.isEmpty()) {
//add lines to the list
aList.add(nxtLn);
}
}
System.out.println();
Random r = new Random();
int randomIndex=r.nextInt(aList.size());
//get the random line
String line=aList.get(randomIndex);
//make 1 d array
//...
}

Categories