Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm currently taking my first java class and have become completely stuck on an exercise. I'm supposed to read data from a text file containing student IDs and their corresponding test scores, have the program grade them then print the results.
I kind of understand the problem, but the book we're working from is kinda hard to read. It all blurs together and I feel like they want me to read two separate things and make a logical leap on how to put them together and I just don't get it.
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
My main issue is that I don't see how I tie the array to the data I have.
I am not gonna post the whole solution but give some steps to start.
Follow this example
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
ArrayList<String> array = new ArrayList<>();
while ((line = reader.readLine()) != null) {
array.add(line);
}
and to split the string like this
str.split(" "); // considering that ids and name are separated by spaces
So, since blanks are allowed in your list of T's and F's, which I assume means the student left the answer to the question blank, you do not have the luxury of using a convenience method like split to easily separate the answers. Instead we use our knowledge that the number of questions must be the same, and id's must have a common length. You can use the substring method to parse out the what you need.
Here's some pseudocode:
final int NUM_QUESTIONS = 25; //I didn't actually count, that's your job
final int ID_LENGTH = 8;
int currentIndex = 0;
//assuming you can fit the whole string in memory, which you should in an intro java class
//do the operations that googling "read a file into a string java" tells you to do in readFileToString
String fileContents = readFileToString("saidFile.txt");
while(fileContents.charAt(currentIndex) != fileContents.length()){
String userAnswers = fileContents.substring(currentIndex, currentIndex+NUM_QUESTIONS);
//move index past userAnswers and the space that separates the answers and the id
currentIndex = currentIndex + NUM_QUESTIONS + 1;
String userId = fileContents.substring(currentIndex, currentIndex+ID_LENGTH)
//move currentIndex past userId and the space that separates the userId from the next set of answers
currentIndex = currentIndex + ID_LENGTH + 1;
//either create an object to store the score with the userId, or print it right away
int score = gradeAnswers(userAnswers)
System.out.println(userId + " scored " + score);
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Basically, I am getting ready for an interview and following a regime that gives me a bunch of challenges that are often thrown in interviews.
This particular challenge's goal is to count the number of words that appear more than once in a sentence excluding punctuations. I did it but it took me at least 5 minutes to come up with it and code it.
I'm not sure if taking 5 minutes is acceptable to code something like this in java interviews so I would like to see something simpler with maybe less code. Below is how I solved it.
System.out.println("Part 6 challenge-------------------------------------------------------------------------");
String sentence3 = "She's the queen and likes, apples APPLES, bananas BANANAS Bananas, and oranges ORANGE."; //original string
StringBuilder sb3 = new StringBuilder(); //declared string builder to build new string without punctuations
char [] punctuations = {'.',',',':','?','!',';'};//Char array containing punctuations to lookout for
for (int i=0; i<sentence3.length(); i++){
boolean p = false; //declared boolean within loop to turn on if punctuation was found in the original string
for (Character c: punctuations){
if (sentence3.charAt(i) == c){
p = true;// turn on
}
} if(!p){
sb3.append(sentence3.charAt(i));//if no punctuations found, add it to the string builder to build new string
}
}
String word[] = sb3.toString().split(" ");
Set<String> uniqueWords = new HashSet<>();
int count = 0;
for (String s: word) {
uniqueWords.add(s.toLowerCase());
}
for (String s: uniqueWords){
for (String w: word){
if (s.equals(w.toLowerCase())){
count++;
}
}
System.out.println(String.format("Found %s %d times", s, count));
count =0;
}
A shorter way, outlined:
Split by regexp;
Filter for words (may be not needed depending on your regexp);
Replace Set<String> with a Map<String, Integer> and count word quantities in linear time;
Filter out and output words with count > 1.
BTW this can all be one stream expression if you're into minimal statement count.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am having a bit of a hiccup with this ArrayList. I am trying to store one or more elements from a String array into an Array list and assigning it to some string variable. My goal is to store keywords into an array list which i could use to search a text file. I can't seem to store found keywords into the array list Can someone help me figure this issue out? Here's some snippets from my code.
public static void main(String args[]) throws ParseException, IOException
{
List<String> matches = new ArrayList<String>();
String[] keywords = {"day", "book", "office", "hour",
"date of a test", "number of assignments", "sure",
"current assignment", "due day"};
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
int count = 0;
for (int i = 0; i < keywords.length; i++) {
if (input.contains(keywords[i])) {
matches.add(keywords[i]);
parseFile(keywords[i]);
}
}
}
And here is my parseFile method
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
// break;
}
}
}
One of the first things I'd do, is check that the stuff is actually going in to the array, so I'd have this:
if(matches.size() == 0)
{
System.out.println("There's nothing in here");
}
That way at least you know that there's nothing there, so then there's no point doing the rest of the program. You should always test your exit condition early where possible that way you save a bit of time, and energy, and allows for quicker debugging. But I digress.
So to add the stuff in to the array list you'd need to do the following:
for (int i = 0; i < keywords.length; i++)
{
String value = keywords[i];
System.out.println("Current Value is: " + value);
matches.add(value);
}
You can't just add an array element as the add method in ListArray is expecting a String. So you need to set the current content of the array to a String then pass THAT in to your matches.add function as above, so when I ran that program on my box, (just the main bit that is) I got the following output.
Current Value is: day
Current Value is: book
Current Value is: office
Current Value is: hour
Current Value is: date of a test
Current Value is: number of assignments
Current Value is: sure
Current Value is: current assignment
Current Value is: due day
Size of matches is: 9
Matches[i]: day
Matches[i]: book
Matches[i]: office
Matches[i]: hour
Matches[i]: date of a test
Matches[i]: number of assignments
Matches[i]: sure
Matches[i]: current assignment
Matches[i]: due day
Also for the record, you need to do the same when you're iterating through your matches as well, so let's say you want to print out your ArrayList, then you'd need to do the following:
for(int i = 0; i < matches.size(); i++)
{
String value = matches.get(i);
System.out.println("Matches[i]: " + value);
}
You'd need to get the string within the array list, you can't just give it an index, as that will not work, again you need to assign it to a string and then pass that back.
If in doubt, dive on to the Java ArrayList API, and have a look at what arguments the functions take.
Hope that helps.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.
Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help
In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to store all possible substring in String []. I tried this but got an error:
public void sub(String word){
String [] Str=new String[100];
int n=0;
for (int from = 0; from < word.length(); from++) {
for (int to = from + 1; to <= word.length(); to++) {
str[n]=word.substring(from, to);
n++;
System.out.println(str[n]);
}
}
}
What is solution?
error is: cannot find symbol, variable str, loction: class substring
Well, that fairly clearly tells you what the error is: You haven't declared str. You have declared Str, but Java's identifiers are case sensitive, str and Str are not the same identifier.
So change
String [] Str=new String[100];
to
String [] str=new String[100];
// ^--- lower case
Before, when you hadn't said what the error was, there were a couple of other things Pshemo and I (amongst others) noticed:
You have a sequence issue here:
str[n]=word.substring(from, to);
n++;
System.out.println(str[n]);
...since you're incrementing n before outputting the string, you're always going to output null. Just moving the increment fixes that:
str[n]=word.substring(from, to);
System.out.println(str[n]);
n++;
Another possible problem can occur for longer words, where number of substrings can be more then 100. In that case you should avoid creating fixed size array, but try using dynamic size collection like List
List<String> str = new ArrayList<String>();
To put or read elements here just use str.add(substring) and str.get(index).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hi I am figuring out how to split the strings so heres my code:
because i using bufferedreader and i have two textboxes so it reads both the text boxes (the 1st textbox i type john), the second textbox i type peter) the output is johnpeter so i trying to split the textboxes instead of reading just 1 line straight.
BufferedReader reader = new BufferedReader(new InputStreamReader(
req.getInputStream()));
String name;
while ((name = reader.readLine().toString()) != null)
{
Statement stmt;
String[] players = name.split("");
String playerO = players[1];
String playerX = players[2];
Current output is:
Player 1 :j
Player 2 :o
I would like my output to be:
Player 1 :john
Player 2 :peter
As is, you won't be able to split the string where you want to, as there's no clear delimiting character. If you stored it as "john peter" or "john,peter" or something like that, it would be easier to split.
Then you would just need to change
String[] players = name.split("");
to
String[] players = name.split(" ");
or String[] players = name.split(",");
Also, as others have mentioned, remember that the first item in players is players[0], not players[1]
As others have alluded to, your original string "johnpeter" needs to instead be something like
"john,peter,joey,tom,dick,harry";
then you can
String name = "john,peter,joey,tom,dick,harry";
String[] players = name.split(",");
String playerO = players[0];
String playerX = players[1];
System.out.println("Player 1 :" + players[O]);//or, playerO
System.out.println("Player 2 :" + players[1]);//or, playerX
Note the zero-base of the array, as well. Hope this helps!
I am not sure what you trying to do since split("on what").
Try some thing like this if space between names,
String name = "john peter";
String[] players = name.split(" ");
String playerO = players[0];
String playerX = players[1];
System.out.println("Player 1 :" +playerO);
System.out.println("Player 2 :" +playerX);
If you want to split("??") there should be (split on what) identifier