Im trying to write a program with three instance methods, but I cant seem to get it right. My method wordCount returns the number of lines in the file. Not the number of words as its supposed to.
Im just lost in the method mostFrequentWords..
Hope someone can help me out
package opgaver;
import java.util.*;
import java.io.*;
public class TextAnalysis14 {
Scanner file;
int CountWords = 0;
boolean Contains = true;
String[] words;
String[] MFwords;
public TextAnalysis14(String sourceFileName, int maxNoOfWords) {
String wordline;
words = new String[maxNoOfWords];
String[] line;
try {
file = new Scanner(new File(sourceFileName));
} catch (FileNotFoundException e) {
file = new Scanner("");
}
while (file.hasNext()) {
wordline = file.next();
line = wordline.split("[^a-zA -Z]+");
for (int i = 0; i < line.length; i++) {
if (!line[i].equals(" ")) {
words[CountWords] = line[i];
CountWords++;
}
}
}
if (words[CountWords] == (null)) {
for (int i = CountWords; i < maxNoOfWords; i++) {
words[i] = ("empty");
}
}
}
public int wordCount() {
return CountWords;
}
public boolean contains(String word) {
for (int i = 0; i < words.length; i++) {
if (words[i].contains(word)) {
return Contains;
}
}
return false;
}
public String[] mostFrequentWords() {
Arrays.sort(words);
return MFwords;
}
}
Because of my noob status I cannot make a comment but it looks like you have a space in your regex between A and -Z.
try with this.
public static void main(String[] args) {
String str = "this is a space String"; // read all lines in a file
String[] splited = str.split(" ");
List<String> list = new ArrayList<String>();
for(int i = 0;i < splited.length; i++){
if(splited[i].length() > 0){
list.add(splited[i]);
}
}
System.out.println(list.size());
}
by calling wordline = file.next(); you are not reading lines.
In TextAnalysis14 change your condition to file.hasNextLine() and read lines with file.nextLine()
while (file.hasNextLine()) {
wordline = file.nextLine();
....
}
You can try something like that using Java 8:
Stream<String> lines = Files.lines(Paths.get("c:/", "file.txt"));
in wordCount = lines.mapToInt(s -> s.split(' ').length()).sum();
This function just cound a words count in file.
Related
Completely new to java and having a nightmare! I have a list of 235886 words shuffled.txt, that I've managed to sort into ascending order, however it takes a lifetime to run, so I was thinking would it be possible to save my results to a txt file. How would I go about this?
All help gratefully received.
Cheers
public class Main {
static final int NUMWORDS = 235886;
static final String FILENAME = "shuffled.txt";
public static void main(String[] args) {
String[] words = readWords(FILENAME, NUMWORDS);
String[] myStringArray = readWords(FILENAME, NUMWORDS);
sortedWords(words);
}
// 5. Write code to build a sorted version of the list (in ascending order)
public static void sortedWords(String unsorted[]) {
sort(unsorted);
for (int n=0 ; n < unsorted.length; n++ ) {
System.out.println(unsorted[n]);
// return unsorted;
}
}static void sort(String[] unsorted){
for (int i =0; i< unsorted.length; i += 1) {
int j = findMinIndex(unsorted, i + 1, i);
if (j != -1) {
swap(unsorted, i, j);
}
}
}
static int findMinIndex(String[] numbers, int startIndex, int minIndex) {
if (numbers.length <= startIndex) {
return -1;
}
for (int i=startIndex; i < numbers.length; i += 1){
if (numbers[i].length() > numbers[minIndex].length()){
minIndex = i;
}
}
return minIndex;
}
static void swap(String[] numbers, int i, int j) {
String tmp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = tmp;
}
private static String[] readWords (String filename,int count){
String[] words = new String[count];
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
int i = 0;
for (String line; (line = br.readLine()) != null && i < count; ) {
words[i++] = line;
}
} catch (java.io.IOException e) {
System.err.println("File: " + filename + " could not be found.");
}
return words;
}
}
"Save my results to a txt file." This is how you put every single from your String[] words array.
import java.io.FileWriter;
String[] words; //Imagine this has a lot of data inside
try {
FileWriter writer = new FileWriter("output.txt");
for(String str: words) {
writer.write(str);
writer.write("\n");
}
writer.close();
}
catch (Exception e)
{
System.out.println("EXCEPTION: " + e);
}
You could change your method sortedWords into this one (needs Java 8 or 9):
public static void sortedWords(String unsorted[]) throws FileNotFoundException {
sort(unsorted);
try(PrintWriter out = new PrintWriter("sorted_words.txt")) {
Arrays.stream(unsorted).forEach(out::println);
}
}
That should do the trick and be relatively simple. Below is an alternative that will support UTF-8 for supporting a wider range of characters:
public static void sortedWords(String unsorted[]) throws IOException {
sort(unsorted);
try(PrintWriter out = new PrintWriter(new OutputStreamWriter(
new FileOutputStream("sorted_words.txt"), "UTF-8"), true)) {
Arrays.stream(unsorted).forEach(out::println);
}
}
You might have to change the signature of the main method to this:
public static void main(String[] args) throws IOException
so that the code compiles.
Remove the for-loop with println inside sortedWords(). After the call to sortedWords in main add this to output to the sorted_words.txt file:
java.nio.file.Files.write(Paths.path("sorted_words.txt"), Arrays.asList(words));
Here I am trying to determine if a word or phrase is a palindrome by using stacks and queues depending on the phrase I write in.
What it is doing is that it says that everything is a palindrome and writes "Palindrome" by how many letters it has.
I'm guessing that I need to add something between the last for loop and the while loop, but I'm not sure what.
public class CheckPalindrome {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.toLowerCase().equals("quit")) {
break;
}
Stack<Character> stack = new Stack<Character>();
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < line.length(); i++) {
stack.push(line.charAt(i));
}
for (int i = line.length() - 1; i >= 0; i--) {
queue.add(line.charAt(i));
}
while (!queue.isEmpty()) {
if (queue.remove().equals(stack.pop())) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
}
}
I made some very minor modifications (first to fix one of your for loops, and second to prevent your "Palindrome/Not a Palindrome" message from printing once for every character in the input) to your code to get it to work:
import java.util.Stack;
import java.util.LinkedList;
import java.util.Queue;
import java.io.*;
class Palindrome {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.toLowerCase().equals("quit")) {
break;
}
Stack<Character> stack = new Stack<Character>();
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < line.length(); i++) {
stack.push(line.charAt(i));
}
for (int i = 0; i < line.length(); i++) {
queue.add(line.charAt(i));
}
boolean isPalindrome=true;
while (!queue.isEmpty()) {
if (queue.remove().equals(stack.pop())) {
continue;
} else {
isPalindrome=false;
break;
}
}
if (!isPalindrome) {
System.out.println("Not a Palindrome");
} else {
System.out.println("Palindrome");
}
}
}
}
You need to put the characters into each of the stack and the queue in the same order. The point of using both is that one reverses the order and the other doesn't. Reversing the order yourself on one of them, as you are doing now, negates that.
Incase it's of interest, here's a variation on your approach using a Deque<E> as opposed to a Stack and Queue separately. A Deque is just a double ended queue (i.e. operates as both).
public static boolean isPalindrome(String word) {
boolean isPalindrome = word.length() == 1;
if (!isPalindrome) {
Deque<Character> wordDeque = new LinkedList<>();
for (Character c : word.toCharArray()) {
wordDeque.add(Character.toLowerCase(c));
}
isPalindrome = true;
while (isPalindrome && wordDeque.size() > 1) {
isPalindrome = wordDeque.pollFirst().compareTo(wordDeque.pollLast()) == 0;
}
}
return isPalindrome;
}
Here is new Solution. Try this one. If any modification ,let me know.
package Stack;
public class pallindrome {
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
void pushh(int new_Data) {
stack.push(new_Data);
}
void enquee(int new_Data) {
queue.add(new_Data);
}
int popStack(){
return stack.pop();
}
int dequeueQueue() {
return queue.remove();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
scan.close();
// Convert input String to an array of characters:
char[] s = input.toCharArray();
// Create a Solution object:
pallindrome p = new pallindrome();
// Enqueue/Push all Integer to their respective data structures:
for(int i=0;i<input.length();i++)
{
p.pushh(i);
p.enquee(i);
}
// Pop/Dequeue the chars at the head of both data structures and compare them:
boolean isPalindrome = true;
for ( i = 0; i < s.length/2; i++) {
if (p.popStack() != p.dequeueQueue()) {
isPalindrome = false;
break;
}
}
//Finally, print whether string s is palindrome or not.
System.out.println( "The Integer, " + input + ", is "
+ ( (!isPalindrome) ? "not a palindrome." : "a palindrome." ) );
}
}
Using both stack and queue together for checking palindrome in JAVA
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the String:: ");
String real = input.nextLine();
Queue q = new LinkedList();
Stack st = new Stack();
for(int i=0; i<=real.length()-1; i++) {
q.add(real.charAt(i));
}
for(int i=0; i<real.length(); i++) {
st.push(real.charAt(i));
}
if(q.remove().equals(st.pop())) {
System.out.println("Palindrom");
}else {
System.out.println("Not Palindrom");
}
}
}
I am trying to create a dictionary out of a .txt file.The problem I think is in my addToDict method. I am trying to resize th array when its full because I am reading from a text file of unknown size but I can only use arrays. I get an out of bounds exception when I am printing the array. I have no idea whats wrong and I have been working on the project for days now. I am also having trouble with my else statement in my addToDict method. It is also and out of bounds exception
import java.io.*;
import java.util.Scanner;
import java.util.regex.*;
public class BuildDict {
static String dict[] = new String[20];
static int index = 0;
public static void main(String args[]) {
readIn();
}
public static void readIn() {
File inFile = new File("alice.txt");
try {
Scanner scan = new Scanner(inFile);
while (scan.hasNext()) {
String word = scan.next();
if (!Character.isUpperCase(word.charAt(0))) {
checkRegex(word);
}
}
scan.close();
} catch (IOException e) {
System.out.println("Error");
}
}
public static void addToDict(String word) {
if (index == dict.length) {
String newAr[] = new String[index * 2];
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
dict = newAr;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}
} else {
dict[index] = word;
index++;
}
}
public static void checkRegex(String word) {
String regex = ("[^A-Za-z]");
Pattern check = Pattern.compile(regex);
Matcher regexMatcher = check.matcher(word);
if (!regexMatcher.find()) {
addToDict(word);
}
}
}
You haven't assigned the new array to dict.
if (index == dict.length) {
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}
// Assign dict to the new array.
dict = newAr;
} else {
dict[index] = word;
index++;
}
The value of index is 0 when the following statement is executed.
String newAr[] = new String[index*2];
Try revisiting your logic. index should be given a positive value before this method is called. That's why you are getting OutOfBounds.
EDIT: Did you mean to write index+2?
You have
static int index = 0;
You need to change the value of this variable, based on your file, otherwise you will always have an error in this line
String newAr[] = new String[index*2];
Instead of using a array use a arraylist for when you don't know the size of your array. It will save you a lot of trouble. I find they are much easier to work with in general then normal arrays.
ArrayList<String> dict = new ArrayList<>();
dict.add(word);
//displaying values
for( int i = 0; i < dict.size(); i++ ){
System.out.println(dict.get(i));
}
I'm trying to make a method that will take an array of strings and return an array with all the words in reverse order but my code is not working.
When I run it i get "[Ljava.lang.String;#74122d9c"
Test case: String[]words={"Monday","Tuesday","Wednesday"}; -->{"yadnoM","yadsueT","yadsendeW"};
public String[] reverseString(String[] words)
{
String[] t=new String[words.length];
for(int i=0;i<words.length;i++)
{
for(int j=words[i].length()-1;j>=0;j--)
{
t[i]+=words[i].substring(j,j+1);
}
}
return t;
}
When I run your code, I didn't get the same error that you posted, but I did notice that null was at the end of each reversed word.
nullyadnoM
nullyadseuT
nullyadsendeW
Which is beacuse when you create a new string array, all it's values default to null:
String[] t = new String[words.length];
The easiest way to fix it is to set it's value to an empty string, before you start adding to it:
public static String[] reverseString(String[] words)
{
String[] text = new String[words.length];
for (int i = 0; i < words.length; i++)
{
text[i] = "";
for (int j = words[i].length() - 1; j >= 0; j--)
text[i] += words[i].charAt(j);
}
return text;
}
I have tested this code, and it works perfectly fine for me.
To output the array, instead of using
System.out.println(words);
use the following:
System.out.println(Arrays.toString(words));
This will give you the output:
[yadnoM, yadseuT, yadsendeW]
You can transform your string into StringBuilder and it had reverse method. And its always better to use foreach rather than for, until there is actual need.
public String[] reverseString(String[] words) {
String[] t = new String[words.length];
for (String wordTemp : words) {
StringBuilder sb = new StringBuilder(wordTemp);
t[i] = sb.reverse().toString();
}
return t;
}
Alternate approach :-
public String[] reverseString(String[] words)
{
String[] t=new String[words.length];
for(int i=0;i<words.length;i++)
{
//added for setting elemennt as emptyString instead of null
t[i] = "";
for(int j=words[i].length()-1;j>=0;j--)
{
t[i]+=words[i].substring(j,j+1);
}
}
//using loop
for(int i=0;i<words.length;i++)
{
System.out.println(t[i]);
}
//using Arrays Method
System.out.println(Arrays.toString(t));
return t;
}
try using StringBuilder.reverse
public String[] reverseString(String[] words) {
String[] t = new String[words.length];
for (int i = 0; i < words.length; i++) {
t[i]= new StringBuilder(words[i]).reverse().toString();
}
return t;
}
Update
The fact that you are getting When I run it i get "[Ljava.lang.String;#74122d9c" is beccase you are printing the whole String array as one [Ljava.lang.String means String array. You will need to iterate over the array to print out the Strings one-by-one
public static void main(String[] args) {
String[] words = { "Monday", "Tuesday", "Wednesday" };
for (int i = 0 ; i < words.length ; i++) {
words[i] = Reverse(words[i]);
}
for (int i = 0 ; i < words.length ; i++) {
System.out.println(words[i]);
}
}
private static String Reverse(String str) {
StringBuilder result = new StringBuilder();
StringTokenizer st = new StringTokenizer(str, "");
while (st.hasMoreTokens()) {
StringBuilder thisToken = new StringBuilder(st.nextToken());
result.append(thisToken.reverse() + " ");
}
return result.toString();
}
Output
yadnoM
yadseuT
yadsendeW
Also you can use org.apache.commons.lang3.StringUtils;, just to reduce your effort/shorten the code
private static String Reverse(String str) {
return StringUtils.reverse(str);
}
Below Code is working fine with the help Stringbuilder reverse function.
public class Example {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] irreverseStr = {"Monday","Tuesday","Wendesday","Thursday","Friday","Saturday","Sunday"};
String[] reverseStr = new Example().getReverseArray(irreverseStr);
for(int j = 0; j < reverseStr.length; j++){
System.out.println(reverseStr[j]);
}
}
public String[] getReverseArray(String[] str){
String [] reversestr = new String[str.length];
for(int i=0;i<reversestr.length;i++){
reversestr[i] = new StringBuilder(str[i]).reverse().toString();
}
return reversestr;
}
}
public static String[] reverseString(String[] words) {
String[] t = new String[words.length];
for (int i = 0; i < words.length; i++) {
t[i]=new StringBuffer(words[i]).reverse().toString();
}
return t;
}
try StringBuffer's reverse method
java 8+
public String[] reverseStringArray(String[] test){
String[] result = Arrays.stream(test).map(item -> {
List<String> list = Arrays.asList(item.split(""));
Collections.reverse(list);
return String.join("", list);
}).collect(Collectors.toList()).toArray(new String[0]);
return result;
}
i have to do a program which takes a sentence and reverses it word by word in java. for eg:
India is my country
output:aidnI si ym yrtnuoc
ive figured out all of it but i just cant split a sentence into separate words.im not allowed to use split function but im meant to use either substring or indexof();while loop and for loop are allowed.
this is what ive got so far:
import java.io.*;
public class Rereprogram10
{
public void d()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("input a string");
str=br.readLine();
String rev="";
int length=str.length();
int counter=length;
for(int i=0;i<length;i++)
{
rev=rev+str.charAt(counter-1);
counter--;
}
System.out.println("the result is: "+rev);
}
}
its wrong though,the output keeps on coming:
yrtnuoc ym si aidnI
i havent learnt arrays yet...
I'm going to assume that advanced datastructures are out, and efficiency is not an issue.
Where you are going wrong is that you are reversing the entire string, you need to only reverse the words. So you really need to check to find where a word ends, then either reverse it then, or be reversing it as you go along.
Here is an example of reversing as you go along.
int length=str.length();
String sentence="";
String word = "";
for(int i=0;i<length;i++) {
if (str.charAt(i) != ' '){
word = str.charAt(i) + word;
} else {
sentence += word +" ";
word = "";
}
}
sentence += word;
System.out.println("the result is: "+sentence);
This passes the test:
package com.sandbox;
import com.google.common.base.Joiner;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
#Test
public void testQuestionInput() {
String input = "India is my country";
assertEquals("country my is India", reverseWords(input));
}
private String reverseWords(String input) {
List<String> words = putWordsInList(input);
Collections.reverse(words);
return Joiner.on(" ").join(words);
}
private List<String> putWordsInList(String input) {
List<String> words = new ArrayList<String>();
String word = "";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == ' ') {
words.add(word);
word = "";
} else {
word += c;
}
}
words.add(word);
return words;
}
}
Here is my code without split() for you.
Input:
India is my country
Output:
country my is India
aidnI si ym yrtnuoc
You can choose the output you need.
public class Reverse {
public static class Stack {
private Node[] slot = new Node[1000];
private int pos = 0;
private class Node{
private char[] n = new char[30];
private int pos = 0;
public void push(char c) {
n[pos++] = c;
}
public String toString() {
return new String(n).trim() + " "; // TODO Fix
}
}
public void push(char c) {
if(slot[pos] == null)
slot[pos] = new Node();
if(c != ' ') {
slot[pos].push(c);
} else {
slot[pos++].push(c);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = pos; i >=0; i --)
sb.append(slot[i]);
return sb.toString();
}
private String reverseWord(String word) {
StringBuilder sb = new StringBuilder();
int len = word.length();
for(int i = len - 1; i >= 0; i--)
sb.append(word.charAt(i));
return sb.toString();
}
public String foryou() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < pos + 1; i ++)
sb.append(this.reverseWord(slot[i].toString()));
return sb.toString();
}
}
/**
* #param args
*/
public static void main(String[] args) {
Stack stack = new Stack();
String sentence = "India is my country";
System.out.println(sentence);
for(int i = 0; i < sentence.length(); i ++) {
stack.push(sentence.charAt(i));
}
System.out.println(stack);
System.out.println(stack.foryou());
}
}
try this
String x="India is my country";
StringBuilder b=new StringBuilder();
int i=0;
do{
i=x.indexOf(" ", 0);
String z;
if(i>0){
z=x.substring(0,i);
}
else{
z=x;
}
x=x.substring(i+1);
StringBuilder v=new StringBuilder(z);
b.append(v.reverse());
if(i!=-1)
b.append(" ");
System.out.println(b.toString());
}
while(i!=-1);