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!
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
I want to make a dialog box popup when I press a letter on the keyboard. This way I made it, I have a really long char array. Is there a better way to make this code?
#Override
public void keyPressed(KeyEvent e) {
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char c = e.getKeyChar();
char a = alphabet[0];
for(int i = 0; i < alphabet.length;i++) {
a = alphabet[i];
if(c == a)
JOptionPane.showMessageDialog(panel, "Error: "+c, " cannot be used", JOptionPane.WARNING_MESSAGE);
}
}
A regex for any single lowercase character would be less code, if your definition of better is less lines.
private String _regex = "[a-z]";
private Pattern _lowercaseCharacterPattern = Pattern.compile(_regex);
#Override
public void keyPressed(KeyEvent e) {
char c = e.getKeyChar();
if( _lowercaseCharacterPattern.matcher(String.valueOf(c) ).matches() )
JOptionPane.showMessageDialog(panel, "Error: "+c, " cannot be used", JOptionPane.WARNING_MESSAGE);
}
Keeping it simple, you could use .contains() on a String of 'valid' characters.
Something like:
private final String letters = "abcdefghijklmnopqrstuvwxyz";
#Override
public void keyPressed(KeyEvent e) {
char c = e.getKeyChar();
// if the character entered is not the list of valid inputs, warn user
if( !letters.contains(Character.toString(c)) ){
JOptionPane.showMessageDialog(panel, "Error: "+c, " cannot be used", JOptionPane.WARNING_MESSAGE);
}
}
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().
Sorry this is probably a dumb question. I'm kinda new to coding and I'm using Processing, which is based off Java.
I have an array of 5 rectangle objects in my main program
for (int i = 0; i < portals.length; i++)
{
portals[i] = new Portals();
}
when displayed, I call this method from my Portals class
void display()
{
rectMode(CENTER);
rect(xLoc, yLoc, rad, 30);
}
the xLoc and yLoc are determined randomly. How would you go about assigning a number (like an identity) to each object in the array so that I can refer to that specific rectangles's location and where would I put it in my code?
You can have a filed in the class that makes it identifiable. Like:
public class Portals {
int xLoc;
int yLoc;
String name;
...
public Portals(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Then you can try to access by name in array
for (int i = 0; i < portals.length; i++)
{
portals[i] = new Portals("Name");
}
for (Portals p : portals){
if ("Name".equals(p.getname()) {
// do somthing
}
}
Or you can use a Map. But that may be more advanced than your knowledge, so I won't give code. But that's another suggestion.
Edit: with Map
Map<String, Portals> map = new HashMap<String, Portals>();
Key Value
map.put("nameForPortal", new Portals());
map.put("anotherNameForPortal", new Portals());
// To access the portal, you can get by the key
Portals p = map.get("nameForPortal");