I am working on creating a program that reads strings in from a data file calles "palindromes.txt" and which stores the strings in a one-dimensional array. The program is supposed to inspect each of the strings and detrmine whether or not each one is a pallindrome. It's supposed to show output on the screen and into a file called "output.txt".
The problem i'm having is that I can't figure out how to get the input/output correct and i'm not sure the best way to utilize the arrays.
Very new to this, please advise if you can. :)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Palindromes2
{
public static boolean isPalindrome(String dirtystr)
{
dirtystr = dirtystr.toLowerCase().replaceAll("[^a-zA-Z]+","");
int length = dirtystr.length(), middle = length / 2;
for (int x = 0; x < middle; x++)
if (dirtystr.charAt(x) != dirtystr.charAt(length - x - 1))
return false;
return true;
}
public static void main(String[] args) throws IOException
{
File inputFile = new File("output.txt");
try (Scanner scanner = new Scanner(inputFile))
{
while (scanner.hasNextLine())
{
String dirtystr = scanner.nextLine();
if (isPalindrome(dirtystr))
{
System.out.println(dirtystr + " IS a palindrome.");
}
else
{
System.out.println(dirtystr + " is NOT a palindrome.");
}
}
}
}
}
Related
Write a program that shall calculate the vocabulary richness of a text in a file and the frequency of the most common word. The vocabulary richness is the number of words in the text divided by the number of distinct words. The frequency of a word is the number of times the word is mentioned in the text divided by the total number of words in the text.
Define and implement class WordCounter with two private fields String word and int count, constructor WordCounter(String word), and public methods String getName(), int getCount(), and void addToCounter().
Define and implement class Corpus (as in text corpus) with one private field ArrayList<WordCounter> words, constructor Corpus(BufferedReader infile), and public methods double getVocabularyRichness() and String getMostFrequentWord().
Implement a test program (as the public static void main method in Corpus) that reads all files in a specific folder, creates a Corpus object from each (previously opened) file, and saves the requested statistics into another file stats.csv. You can either create a new Corpus object for each file or define an ArrayList<Corpus> of the corpora.
Each line of the CSV file must consist of three fields separated by commas (but no spaces!): the file name, the vocabulary richness, and the most frequently used word. Run your program on all Shakespeare's plays. Submit the CSV file together with the Java file.
I wrote what I think is the correct implementation of the HW problem because it works properly for some of the text files, however only the words.get(i).getName() (I tested with words.get(i).getCount()) method will print a blank space for some of the files. I have tried everything, and can't seem to figure it out. Can you please give me a hint or some guidance as to how to fix this issue?
public class Corpus {
private ArrayList<WordCounter> words = new ArrayList <WordCounter>() ;
Corpus(BufferedReader infile){
String ln;
try {
while((ln = infile.readLine()) != null) {
for (String word : ln.toLowerCase().split("([,.\\s]+)")) {
int reference = 0;
for(int i = 0; i < words.size(); i++) {
if (word.equals(words.get(i).getName())) {
reference++;
words.get(i).addToCounter();
} }
if (reference==0) { words.add(new WordCounter(word)); }
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public double getVocabularyRichness() {
int word_count=0;
for(int i = 0; i < words.size(); i++) {
word_count=word_count+words.get(i).getCount();
}
return (double)word_count/(double)words.size();
}
public String getMostFrequentWord() {
String winner = "*AN ERROR OCCURRED*";
int max_count = 0;
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() > max_count){
max_count = words.get(i).getCount();
}
}
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() == max_count){
winner = words.get(i).getName();
}
}
//winner="Test " + String.valueOf(words.get(i).getName());;
//return String.valueOf(max_count);
return winner;
}
public static void main(String [] args) throws Exception{
BufferedWriter writer = null;
File folder_location = new File("/Users/joaquindelaguardia/Desktop/Shakespeare");
File[] file_array = folder_location.listFiles();
for(File iteration_file: file_array) {
FileReader current_file = new FileReader(iteration_file);
BufferedReader infile = new BufferedReader(current_file);
Corpus obj1 = new Corpus(infile);
String file_name = iteration_file.getName();
String frequent_word = obj1.getMostFrequentWord();
String vocabulary_richness = String.valueOf(obj1.getVocabularyRichness());
System.out.println(file_name);
System.out.println(frequent_word);
System.out.println(vocabulary_richness);
System.out.println("-----------------------------");
//FileWriter file_writer = new FileWriter("/Users/joaquindelaguardia/Desktop/stats.csv");
//writer = new BufferedWriter(file_writer);
//String output = file_name+", "+frequent_word+", "+vocabulary_richness + "\n";
//writer.append(output);
}
//writer.close();
}
}
public class WordCounter {
private String word;
private int count=1;
WordCounter(String word){
this.word=word;
}
public String getName() {
return word;
}
public int getCount() {
return count;
}
public void addToCounter() {
count++;
}
}
Im testing the information by printing before appending to file, and as you can see with the small fragment of the output included below, for some cases it prints the most common word (and) while in the second case it doesn't print anything.
shakespeare-lovers-62.txt
and
2.2409948542024014
shakespeare-julius-26.txt
6.413205537806177
In this code, how do I call an array globally for other methods to use?
Background info on my code, we are asked to scan a file that contains DNA strands then translating it to an RNA Strand.
I receive the error: " cannot find symbol - variable dna " when i call the dna array on the translation method (it can't find dna.length) for(int i=0; i < dna.length; i++){
public class FileScannerExample
{
public static void main(String[] args) throws IOException
{
//This is how to create a scanner to read a file
Scanner inFile = new Scanner(new File("dnaFile.txt"));
String dnaSequence = inFile.next();
int dnalength = dnaSequence.length();
String[] dna = new String[dnalength];
for(int i=0; i<=dna.length-2 ; i++)
{
dna[i]=dnaSequence.substring(i,i+1); //looking ahead and taking each character and placing it in the array
}
dna[dna.length-1]=dnaSequence.substring(dna.length-1); //reading the last spot in order to put it in the array
//Testing that the array is identical to the string
System.out.println(dnaSequence);
for(int i = 0 ; i<=dna.length-1; i++)
{
System.out.print(dna[i]);
}
}
public void translation()
{
for(int i=0; i < dna.length; i++){
//store temporary
if (dna[i] = "A"){
dna[i] = "U";
}
if(dna[i] = "T"){
dna[i] = "A";
}
if(dna[i] = "G"){
dna[i]= "C";
}
if(dna[i] = "C"){
dna[i] = "G";
}
}
}
}
you need to bring the symbol into scope before you can reference it. you can do this, either by pulling it up into a higher scope (as a field in the class), or by sending it into the local scope by passing it as a method parameter.
As a class member:
public class Test
{
private String myField;
void A() {
myField = "I can see you";
}
void B() {
myField = "I can see you too";
}
}
As a method parameter:
public class Test
{
void A() {
String myVar = "I can see you";
System.out.println(myVar);
B(myVar);
}
void B(String param) {
param += " too";
System.out.println(param);
}
}
Note that in order to see an instance member, you must be referencing it from a non-static context. You can get around this by declaring the field as static too, although you want to be careful with static state in a class, it generally makes the code more messy and harder to work with.
I'm writing a program but I'm unable to call a few of the methods I made. The errors are as follows:
-method reportMenu(String) in the type CommissionReportSystem is not applicable for the arguments ()
-Cannot make a static reference to the non-static method getSalesData() from the type CommissionReportSystem
-The method computeTotalSales() is undefined for the type CommissionReportSystem
-The method computeSalesCommission(double) in the type CommissionReportSystem is not applicable for the arguments ()
-The method showAgentCommission(double) in the type CommissionReportSystem is not applicable for the arguments ()
I've tried a lot of fixes but nothing seems to be sticking and I'm unsure of how to proceed. I've included the relevant parts of the code below. I would appreciate any tips on how to fix any of these. Thank you!
import java.io.*;
import java.text.*;
import java.util.*;
public class CommissionReportSystem {
private static final String String = null;
public static void main(String[] args) {
getSalesData ();
computeTotalSales ();
computeSalesCommission ();
showAgentCommission ();
shutdown ();
}
String [] getSalesData (){
String [] data = new String [2];
String ticketsSold = "";
String ticketPrice = "";
String buffer = new String ();
data[0] = buffer;
data[1] = buffer;
BufferedReader br = null;
try {
br = new BufferedReader (new InputStreamReader(System.in));
System.out.print ("Enter tickets sold:");
buffer = br.readLine ();
ticketsSold = buffer;
System.out.print ("Enter ticket price:");
buffer = br.readLine ();
ticketPrice = buffer;
} catch (Exception e) {
System.out.println ("Invalid entry");
}
data [0] = ticketsSold;
data [1] = ticketPrice;
return data;
}
public static double totalSales (String ticketsSold, String ticketPrice){
int ticketsSoldNum = Integer.parseInt(ticketsSold);
double ticketPriceNum = Double.parseDouble(ticketPrice);
double totalSalesNum = ticketsSoldNum * ticketPriceNum;
return totalSalesNum;}
public static final double computeSalesCommission (double totalSalesNum){
final double rate1 = 0.025;
final double rate2 = 0.0375;
final double rate3 = 0.0425;
final double salesLimit1 = 2000;
final double salesLimit2 = 4000;
final double agentCommission= 0;
if (totalSalesNum <= 2000) {
agentCommission = rate1 * totalSalesNum;
}
else if (totalSalesNum <= 4000){
agentCommission = rate2 * totalSalesNum;
}
else (totalSalesNum > 4000){
agentCommission = rate3 * totalSalesNum;
}
return agentCommission;
}
public static void showAgentCommission (double agentCommission){
System.out.format ("Congratulation agent Cindy Smith, your current daily commission:" + agentCommission);
}
public static void shutdown (){
System.out.format ("Thank you for your time! Have a great day!");
}
public static void handleInvalidData (){
}
}
1) getSalesData() is an instance method. If you want to call an instance method, create an object of the class and call method using that. Else you have to make the method static. Remember one the thing you cannot access the instance variables inside static method.
2) There is no method computeTotalSales() in your class.
3) computeSalesCommission() requires an argument of type double. You have called it without any argument.
4) The last comment is also valid for showAgentCommission().
I'm making a simple program in D that loops around the files present inside a given folder and calculate the MD5 of the file. I have got this program working easily with no problem.
I recently learned more about parallelism and thought that my little program would benefit greatly from it.
I changed the loop around the files to a parallel one, but now it is working weird.
The program starts reading files and calculating their MD5, but sometimes, executing close(file) throw an exception with error code 0. Sometimes, there is just an
Object.Error: Access violation
Sometimes the program just freezes, sometimes it simply crashes.
When I remove the file opening (the loop then basically just print the filename to the console) it works well.
The time it takes for the program to crash is maybe linked to the size of workUnitSize. If not set (default 100), it crashes or stop working after processing around 30-40 files. If I set it to 1, it stops after 2 to 10 files.
Here is the smallest reproducible code I've extracted :
import std.md5;
import std.stdio;
import std.file;
import std.conv;
import std.getopt;
import std.string;
import std.process;
import std.parallelism;
import std.exception;
struct Entry
{
string name;
ubyte[16] md5;
}
int ChunkStep = 4096;
void main(string[] args)
{
string folder1 = args[1];
string folder2 = args[2];
Entry[] entries1;
foreach (name; parallel(dirEntries(folder1, SpanMode.breadth), 1)) // not working
{
if(name.isFile())
{
entries1 ~= Entry(name ,mdFile(name));
}
}
writeln(folder1," has ",entries1.length, " entries");
Entry[] entries2;
foreach (string name; dirEntries(folder2, SpanMode.breadth)) //working fine
{
if(name.isFile())
{
entries2 ~= Entry(name ,mdFile(name));
}
}
writeln(folder2," has ", entries2.length, " entries");
}
/// Digests a file and prints the result.
ubyte[16] mdFile(string filename)
{
MD5_CTX context;
ubyte[16] digest;
context.start();
File f = File(filename,"r");
foreach (buffer; f.byChunk(ChunkStep))
context.update(buffer);
context.finish(digest);
try{
f.close();
}
catch(ErrnoException e)
{
writeln(e.errno);
}
writefln("MD5 (%s) = %s", filename, digestToString(digest));
return digest;
}
I'm using Dmd2.064.2 on Windows 7 64b with a Intel Q6600 (quad core).
Do you use 32bit version of dmd?
update:
seems on windows there is some bug with byChunk (rawRead). So you can use std.stream instead.
import std.md5;
import std.stdio;
import std.file;
import std.conv;
import std.getopt;
import std.string;
static import std.stream;
import std.process;
import std.parallelism;
import std.exception;
struct Entry
{
string name;
ubyte[16] md5;
}
enum ChunkStep = 4096;
void main(string[] args)
{
string folder1 = args[1];
string folder2 = args[2];
Entry[] entries1;
foreach (name; parallel(dirEntries(folder1, SpanMode.breadth), 1)) // not working
{
if(name.isFile())
{
entries1 ~= Entry(name ,mdFile(name));
}
}
writeln(folder1," has ",entries1.length, " entries");
}
/// Digests a file and prints the result.
ubyte[16] mdFile(string filename)
{
MD5_CTX context;
ubyte[16] digest;
context.start();
std.stream.File f = new std.stream.File(filename);
byte[ChunkStep] buffer;
size_t len;
while((len = f.readBlock(buffer.ptr, ChunkStep)) > 0) {
context.update(buffer.ptr[0 .. len]);
}
context.finish(digest);
f.close();
writefln("MD5 (%s) = %s", filename, digestToString(digest));
return digest;
}
My code is suppose to use loops only, I am suppose to make a string reverse and return that reverse value. I have a problem return the reverse value and I have no clue how to do it.`
public static String reverseString(String str){
for(int i =str.length()-1;i>=0;i--)
return str.charAt(i);// This wont return the value, gives me a error
// any tips?
}
Assuming you use Java you can change your code to this:
public static String reverseString(String str){
StringBuilder sb = new StringBuilder();
for(int i =str.length()-1;i>=0;i--){
sb.append(str.charAt(i));
}
return sb.toString();
}
The change is that you create a StringBuilder object. The code you posted tries to return the first char you extract from your string which is not what you want. You want to build the string in reverse, so in each iteration you add the next reversed char to your StringBuilder, and when the loop terminates, you return the string representation of the StringBuild by using toString().
You can do this implementation smarter and faster, but I assume that this task is part of a learning process, so it is more important that you understand why your code should not place a return statement in a loop, when you actually want the loop to iterate multiple times and save each intermediate result before returning anything.
Documentation:
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
UPDATE:
Based on ohiodoug's comment about StringBuilder it would be appropriate to also show how it is done without the StringBuilder class:
import java.lang.StringBuilder;
public class Main
{
public static void main(String [ ] args){
String resultSimple = simpleReverseString("Hello World!");
String resultSB = betterReverseString("Hello World!");
System.out.println(resultSimple);
System.out.println(resultSB);
//Prints:
//!dlroW olleH
//!dlroW olleH
}
//Simple string concatenation.
//Uses the += operator.
//Since s is already a String we don't need to use
//toString() on it.
public static String simpleReverseString(String str){
String s = "";
for(int i =str.length()-1;i>=0;i--){
//s += str.charAt(i) is equal to
//s = s + str.charAt(i)
s += str.charAt(i);
}
return s;
}
//Same as simpleReverseString, but uses the StringBuilder class
public static String betterReverseString(String str){
StringBuilder sb = new StringBuilder();
for(int i =str.length()-1;i>=0;i--){
sb.append(str.charAt(i));
}
return sb.toString();
}
}
Updated answer:
public static String reverseString(String str){
char[] temp = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
temp[i] = str.charAt(str.length() - (i + 1));
}
return new String(temp);
}
Good luck!