So I'm having a bit of trouble on one of my assignments. I can't seem to figure out what I need to do. Here is the question:
Points for reading are assigned on the following basis: The first three books read are worth 10 points each. The next three books read are worth 15 points each. All books read over six are worth 20 points each. A student who reads 7 books would be awarded 95 points (30 for the first three plus 45 for the next 3 and 20 for the 7th book).
An external file contains a first and last name followed by an integer (the number of books read)
Print on each persons name, the number of books read and the points earned. The names should be in the order last, first with the only the last name in all capital letters. At the bottom of the list print out the average points for all readers and the winner of the contest.
Statements Required: input, output, decision making, loop control, strings
Data Location: prog700c.dat
Sample Output:
Reading Contest
Name Books Points
SUMMER Sam 4 45
LAZY Linda 2 20
PRODDER Paul 5 60
MASTER K.C. 8 115
READER Richie 6 75
Average points per reader = 63.0
The winner of the contest is K.C. Master
The external file data is this:
SUMMER Sam 4
LAZY Linda 2
PRODDER Paul 5
MASTER K.C. 8
READER Richie 6
My current code:
import java.io.*;
import java.util.*;
public class Prog505a
{
public static void main(String[] args)
{
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\java programs\\Prog700c\\Prog700c.in"));
String data = kbReader.nextLine();
while(kbReader.hasNextLine())
{
I'm having a problem where I don't know what string method to use to only get the numbers from the external file to use them in the calculations. I know I can do the decision making, etc. but I just don't know what to do on this one part to get only the numbers from the external file. If someone could provide some direction or guidance would be greatly appreciated. Thank you!
You can use String.split("\\s+") to split the line into three parts (check if they are three parts to be sure, print a warning and skip if not). This will return an array of strings. You can use Integer.parseInt() to read the number of books on the third item in the array (position 2, arrays in Java are "zero based").
Note that "\\s+" is a regular expression which finds 1 or more parts of whitespace. The strings within the whitespace and the beginning/end of the string are returned. If regular expressions are not allowed, try and find the index of the space-character within the string, and use String.substring() - and don't ignore the return value for string operations.
Alternatively you could use next(), next() and nextInt() instead of nextLine() in your scanner.
You could use regex to deliver what you're saying :
Try to use something like:
str = str.replaceAll("\\D+","");
This way you would delete all non-digits in a string. After that you would need to parse the String to an integer or any other Number type.
Related
I am using Google Guava APIs to calculate word count.
public static void main(String args[])
{
String txt = "Lemurs of Madagascar is a reference work and field guide giving descriptions and biogeographic data for all the known lemur species in Madagascar (ring-tailed lemur pictured). It also provides general information about lemurs and their history and helps travelers identify species they may encounter. The primary contributor is Russell Mittermeier, president of Conservation International. The first edition in 1994 received favorable reviews for its meticulous coverage, numerous high-quality illustrations, and engaging discussion of lemur topics, including conservation, evolution, and the recently extinct subfossil lemurs. The American Journal of Primatology praised the second edition's updates and enhancements. Lemur News appreciated the expanded content of the third edition (2010), but was concerned that it was not as portable as before. The first edition identified 50 lemur species and subspecies, compared to 71 in the second edition and 101 in the third. The taxonomy promoted by these books has been questioned by some researchers who view these growing numbers of lemur species as insufficiently justified inflation of species numbers.";
Iterable<String> result = Splitter.on(" ").trimResults(CharMatcher.DIGIT)
.omitEmptyStrings().split(txt);
Multiset<String> words = HashMultiset.create(result);
for(Multiset.Entry<String> entry : words.entrySet())
{
String word = entry.getElement();
int count = words.count(word);
System.out.printf("%S %d", word, count);
System.out.println();
}
}
The output should be
Lemurs 3
However I am getting like this:
Lemurs 1
Lemurs 1
Lemurs 1
What am I doing wrong?
MultiSet works fine. Take a close look at your results - switching the printf to e.g. "|%S| %d" will help:
|lemurs.| 1
|lemurs| 1
|Lemurs| 1
It is immediately apparent that those are all 3 different strings. The solution in this case is to simply strip all non-alphabetical chars, and lowercase all words.
Using printf("%S %d", words, count) with a capital S hides the detail that the different capitalizations of the word "lemurs" are being counted separately. When I run that program, I see
one occurence of "lemurs." with a period not being trimmed
one occurrence of "lemurs" all lowercase
one occurrence of "Lemurs" with the first letter capitalized
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to multiply numbers from a text file using JAVA but have no idea how.
4
12 4
16 8
14 1
12 8
The first number on the first line represents how many people there are within the document (line 2 "12 4" being the first person "12 8" being the last.)
4 (number of employees)
32 (hours employees have worked) 8 (wage per hour)
38 6
38 6
16 7
I'm trying to find how Java can skip line 1, read line two and multiply the two numbers and then do the same for the other lines.
Please can anyone explain how I could do this?
Cheers!
Here are all the things you need:
To read a file: Java: How to read a text file
To cast to integer: How to convert a String to an int in Java?
To multiply: use * operator
The assumption is that you have been given this as an assignment for homework and either you have not paid attention in class. The key to learning programming, is breaking the task down into manageable tasks.
In your case, write a program to read the input file and echo the output. Once you have that, you are part of the way there.
Next, put the numbers into integer variables. This will involve casting.
Then perform that math and spit out the output.
By performing small tasks, the problem becomes much easier.
I don't really understand your criteria unfortunately, but you seem to be able to understand the formula, and that's all you need. I recommend BufferedReader and FileReader to get the text from the file. From there, it's a good idea to start parsing your Strings around the spaces (there's a method for that), and you can then convert them to integers. Hopefully this puts you on the right track.
You definately need to read upon programming as a whole at first, because this should be one of the basic questions you should be able to answer.
I can give you a rough sketch on how to do it:
Construct a File object out of the place where the 'document' resides.
Read the input, definetely for novices, I would recommend using the Scanner class.
Read the first Integer or Line, save this number.
Read the following pair of Integers or Lines.
Multiply the read numbers.
Output the multiplication result.
You also might want to check some other concerns:
Should your program break on wrong input?
Should your program continue on wrong input?
You should take those things in consideration when reading either the Integers or the Lines out of the document.
I see you are having problems with BufferedReader. So to avoid the overhead of type conversion, you may consider using Scanner.
In your case,
Scanner scanner = new Scanner ("Path to your file with backslash characters escaped");
int myNumber = scanner.nextInt();
It will directly assign the number from the file to your variable.
Create a scanner to read the file
Skip the first line
Iterate over all the numbers
Multiply number pairs
Do something with those numbers
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
// 1. Create a scanner to read the file
Scanner file = new Scanner(new File("textfile.txt"));
// 2. Skip the first line
file.nextLine();
// 3. Iterate over all the numbers
while(file.hasNextInt()) {
int hours = file.nextInt();
int wagePerHour = file.nextInt();
// 4. Multiply number pairs
int totalWage = hours * wagePerHour;
// 5. Do something with those numbers
<do something with the numbers>
}
}
}
This will skip the first line and print out the multiplied values for every following line. This is assuming that you are passing a file as a command-line argument.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Multiply{
public static void main(String[] args) throws FileNotFoundException{
File file = new File(args[0]);
Scanner sc = new Scanner(file);
// skip the first line
sc.nextLine();
int num_people;
int hours;
int total;
while(sc.hasNext()){
num_people = sc.nextInt();
hours = sc.nextInt();
total = num_people * hours;
System.out.println(total);
}
}
}
to start with i want to say this is no homework or somthing, i just want deeper knowledge about these kind of arrays with I/O so feel free to just tell me how you tackle the problem WITH SCANNER, if its solvable :P
if i have a txt file that is like:
car 1 2 3 4 5
boat 1 2 3 4 5
plane 1 2 3 4 5
and i have made a new class in new .java-file which is an abstract 2d array:
class Type
{
String type;
int number;
}
public toString()
{
return String.format("%02d:%02d", type, number);
}
is it possible to get an outprint like:
car:1 car:2 car:3
boat:1 boat:2 boat:3
etc? thanks.
edit: also an ArrayList of course..
edit2:
while (scanner.hasNext())
{
list.add(scanner.hasNext(), 0); //the array should be <car, 0>
} //later i will loop through numbers
The pseudo-code of what I'm suggesting is this:
create line Scanner
while scanner has next *line*
get the next line
use String#split(" ") to create a String array from this line
Create your object from the items in this array
Add your new object into your list
end while loop
First thing that comes to mind is this (assuming your file will always have that structure):
Read your line and use string.split("\\s+"); to break your line into word tokens (\\s+ denotes one or more space in regular expression language).
If you can be certain that the word will always be the first element in the line, then, you can iterate from your 2nd token (your first number) till your last token (your last number) and with each iteration you create a new Type object where the type is the first token and the number is the nth token.
The above should allow you to construct objects which when printed, will yield your desired output.
If on the other hand, the order of the tokens is not known, but you are sure that in every line you will have one word and n numbers, you can use further regular expressions such as ^\\w+$ and ^\\d+$ to see which token is either a word or a digit respectively. Once you know which token is what, you can refer to the above points to get your code to work.
For more information on regular expressions, you can take a look at this tutorial.
Hi I have to write a program that takes in number of candidate and how many votes they got from the best to the worst. And I wrote two different classes to do that using a fileInputStream and another that uses the scanner class and storing it in the arraylist but the way the teacher has it in the text file is that some of the ballots are on different line so they will go like on one line while the ballots are on the other line. so its like this:
//this is how the text appears in the text file and I was wondering if I could get all
//the "votes" to look like the first one.
<v> 5 4 3 2 1
<v> 1 2 3 4 5
<v>
1
2
3
5
<v>
5
2
4
1
3
I think your teacher has done it deliberately. The trick here is to realize that the votes are not delimited by a new line, instead they are delimited by a "V". You can use this information along with regex(Pattern) to derive a solution.
If you don't want to use a regex, you could use Scanner.
if (scanner.hasNext("<v>")
scanner.next();//ignore the "<v>"
if (scanner.hasNextInt())
int vote1 = scanner.nextInt();//first vote
if (scanner.hasNextInt())
int vote2 = scanner.nextInt();//second vote
This would read for example:
<v> 1
4
I don't want to spoil the 'fun' of making your homework, so that's all. If you have more questions, just ask.
I'm operating on a file that has this kind of format:
LAWS303 RHLT1 10 84 AITKEN WU
LAWS314 RHLT3 15 2 PARADZA VISSER
LAWS329 EALT006 6 62 AITKEN WILSON
LAWS334 HMLT105 2 43 ANDREW INKSTER
LAWS334 HMLT206 2 62 JULIAN YOUNG
LAWS340 RHLT1 11 87 AL YANG
The goal of this program is that for each day (the third column) of the month, each course code (first column) should be printed along with the total number of students attending (fourth column) for the course on that day. From my thinkering, this involves either reading the file a lot of times (ew!) or loading the three salient values (day, course, headcount) into some sort of array and operating on that instead. Despite being fairly familiar with what a multi dimensional array is, this one has repeatedly caused my head to implode. I've got the pseudo code for this program written out in front of me and my mind draws a blank when it comes to the line that defines the array.
The dayOfMonth can remain a string because it'll only be compared to another string. The courseCode obviously needs to be a string, too. However, the headCount ideally would be numeric; it'll be added to as each line of the file is processed. The relationship between the three is basically that there can be many courseCodes per dayOfMonth, but only one headCount per courseCode as I'll be adding to it as I read it all into the array.
So, in derpspeak, this is how it should roughly look:
{String dayOfMonth = {{String courseCode}, {int headCount}}}
The two issues I have here, are...
a) that I'm not sure how to actually code this kind of funky array in there and
b) as I can't really wrap my brain around it to begin with, there's a really good chance that I've essentially just designed something completely wrong for what I need. Or impossible. Both?
For example, the array will start off empty. I'd want to add a dayOfMonth, courseCode and headCount to start it off. But I couldn't just go array.add(dayOfMonth) because it's expecting an array, leading me to suspect I should be using something else. Argh!
Oh god my brain.
This looks like homework, so my answer will consist of hints.
Hint #1 - there are some entities in those rows. Work out what they are and write a class for each one.
Hint #2 - Use List types not arrays. Arrays have to be preallocated with the right number of elements.
Hint #3 - Use Map types (e.g. HashMap or TreeMap) to represent mappings from one kind of thing to another kind of thing.
If you want to store and retrieve the values then use #Stephan C's input.
Here is code snippet to print values using sysout. You can modify to hold the values as you wish.
BufferedReader reader = new BufferedReader(new FileReader("< your file here >"));
String string = reader.readLine();
while (string != null) {
StringTokenizer tokenizer = new StringTokenizer(string);
String print = "";
if (tokenizer.countTokens() > 4) {
print = tokenizer.nextToken();
tokenizer.nextToken();
print = tokenizer.nextToken() + " " + print;
print = print + " " + tokenizer.nextToken();
}
System.out.println(print);
string = reader.readLine();
}