We recently started learning about static methods and for this assignment we are making a "String Helper" program that creates a few static methods that modify strings, and this is the task for one of them:
meshStrings: This method takes in two strings via parameters, meshes them together, and returns the meshed strings. Meshing alternates the each character in the first string with every character in the next string. If there are not enough characters to fully mesh then the rest will be appended to the end. For instance if the two strings were "harp" and "fiddle" the returned string will be hfairdpdle.
Here's the start of what I have, I don't have much:
public class StringHelper {
public static String meshStrings (String string1, String string2)
{
}
Driver class:
public class StringHelperTester {
public static void main (String[] args)
{
System.out.print(StringHelper.meshStrings("fiddle", "harp"));
}
I assume you'll have some type of for loop that prints out the charAt length of each string but I'm not exactly sure the best way to set it up. Help is appreciated.
the best way to enchance your skills is to just try ...
public static String meshStrings (String string1, String string2) {
StringBuffer buff = new StringBuffer();
int max = Math.max(string1.length(), string2.length());
for(int i = 0; i < max; i++) {
if(i < string1.length()) {
buff.append(string1.charAt(i));
}
if(i < string2.length()) {
buff.append(string2.charAt(i));
}
}
return buff.toString();
}
KISS : keep it simple and stupid. then you can enhance this code if you want, it's not optimal.
Related
my professor gave me an exercise to find how many time the characters of string called "filter" are to be found in a second string called "query".
before I begin I am java noob and English isnt my native language.
example:
String filter="kjasd";
String query="kjg4t";
Output:2
getting how many times a char has been found in another string isnt my problem but the problem that the professor gave us some rules to stick with:
class filter. The class must be the following public
Provide interfaces:
public Filter (String letters) (→ Constructor of class)
The string representing the filter should be stored in the letters string
public boolean contains (char character)
Returns true if the passed character is contained in the query string, otherwise false
-public String toString ()
Returns an appropriate string representation of the class (just to be clear I have no clue about what does he means with this one!)
To actually determine the occurrences of the filter in the query, another class QueryResolver is to be created.
The class should be able to be used as follows:
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
the filter and the query are given by the user.
(i couldnt understand this one! )The methods "where" and "matches" configure the "QueryResolver" to include a subsequent call of "count" the calculation based on the previously passed variables
"query" and "filter" performs.
The count method should use the filter's previously-created method.
The modifier static is not allowed to use!
I dunno if he means that we cant use static {} or we cant use public (static) boolean contains (char character){}
we are not allowed to use void
so the problems that encountered me
- I can not pass a char to the method contains as long as it is not static.
error "Non-static variable can not be referenced from a static context"
i did not understand what i should do with the method toStirng!
what I've done so far:
Approach Nr 1:
so I just wrote everything in the main method to check whether the principle of my code works or not and then I wanted to create that whole with constructor and other methods but unfortunately I did not succeed.
Approach Nr 2:
then I tried to write the code in small mthoden as in the exercise but I did not succeed !.
in both aprroaches i violated the exercise rules but i cant seem to be able to do it alone thats why i posted the question here.
FIRST APPROACH:
public class filter{
public filter(String letters) {
//constructor of the class
String filter;
int count;
}
public boolean contains (char character){
/*Subprogram without static!
*the problem that I can't pass any char to this method if it wasn't static
*and I will get the following error"Non-static variable cannot be referenced from a static context"
*I understand why I'm getting the error but I don't know how to get around it X( */
return true ;
}
public String toString (){
/*he told us to include it in the program but honestly, I don't know what shall I write in it -_-
*I make it to null because you have to return something and I don't know what to do yet
*so, for now, I let it null. */
return null;
}
public static void main(String[] args) {
Scanner in =new Scanner (System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
int count=0;
// I initialized it temporarily because I wanted to print it!
//later I need to use it with the boolean contains as a public method
boolean contains=false;
//to convert each the query and the filter strings to chars
char [] tempArray=query.toCharArray();
char [] tempArray1=filter.toCharArray();
//to iterate for each char in the query string!
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
//to iterate for each char in the filter string!
for (int j = 0; j < tempArray1.length; j++) {
// if the value in the filter string matches the value in the temp array then increment the counter by one!
if(tempArray1[j] == cc){
count++;
contains=true;
}
}
}
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
System.out.println("the boolean value : "+ contains);
in.close();
}
}
SECOND APPROACH
- But here too I violated the rules of the task quite brutally :(
- First, I used void and did not use the tostring method.
- Second, I did not use a constructor.
- I did not add comments because that's just the same principal as my first attempt.
public class filter2 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("enter the filter string:");
String filterStr=in.next();
System.out.println("enter the query string:");
String querystr =in.next();
Filter(filterStr, querystr);
in.close();
}
public static void Filter(String filterstr , String querystr){
char [] tempArray1 = filterstr.toCharArray();
contains(tempArray1, querystr);
}
public static void contains(char[]tempArray1, String querystr){
boolean isThere= false ;
int counter=0;
char [] tempArray = querystr.toCharArray();
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
for (int j = 0; j < tempArray1.length; j++) {
if(tempArray1[j] == cc){
counter++;
isThere=true;
}
}
}
System.out.println("the letters of the filter string has been found in the query string exactly "+counter+" times!\nthus the boolean value is "+isThere);
}
/*
* sadly enough i still have no clue what is meant with this one nor whatshall i do
* public String toString (){
* return null;
* }
*
*/
}
Few hints and advice would be very useful to me but please demonstrate your suggestions in code because sometimes it can be difficult for me to understand what you mean by the given advice. ;)
Thank you in advance.
(sorry for the gramatical and the type mistakes; english is not my native language)
As already mentioned, it is important to learn to solve those problems yourself. The homework is not for punishment, but to teach you how to learn new stuff on your own, which is an important trait of a computer scientist.
Nonetheless, because it seems like you really made some effort to solve it yourself already, here is my solution, followed by some explanation.
General concepts
The first thing that I feel like you didn't understand is the concept of classes and objects. A class is like a 'blueprint' of an object, and the object is once you instanciated it.
Compared with something like a car, the class would be the description how to build a car, and the object would be a car.
You describe what a class is with public class Car { ... }, and instanciate an object of it with Car myCar = new Car();.
A class can have methods(=functions) and member variables(=data).
I just repeat those concepts because the code that you wrote looks like you didn't fully understand that concept yet. Please ask some other student who understood it to help you with that.
The Filter class
public class Filter{
String letters;
public Filter(String letters) {
this.letters = letters;
}
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
public String toString (){
return "Filter(" + letters + ")";
}
}
Ok, let's brake that down.
public class Filter{
...
}
I guess you already got that part. This is where you describe your class structure.
String letters;
This is a class member variable. It is unique for every object that you create of that class. Again, for details, ask other students that understood it.
public Filter(String letters) {
this.letters = letters;
}
This is the constructor. When you create your object, this is the function that gets called.
In this case, all it does is to take an argument letters and stores it in the class-variable letters. Because they have the same name, you need to explicitely tell java that the left one is the class variable. You do this by adding this..
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
This takes a character and looks whether it is contained in this.letters or not.
Because there is no name collision here, you can ommit the this..
If I understood right, the missing static here was one of your problems. If you have static, the function is class-bound and not object-bound, meaning you can call it without having an object. Again, it is important that you understand the difference, and if you don't, ask someone. (To be precise, ask the difference between class, object, static and non-static) It would take too long to explain that in detail here.
But in a nutshell, if the function is not static, it needs to be called on an object to work. Look further down in the other class for details how that looks like.
public String toString (){
return "Filter(" + letters + ")";
}
This function is also non-static. It is used whenever the object needs to be converted to a String, like in a System.out.println() call. Again, it is important here that you understand the difference between class and object.
The QueryResolver class
public class QueryResolver {
Filter filter;
String query;
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
}
Again, let's break that down.
public class QueryResolver {
...
}
Our class body.
Note that we don't have a constructor here. It is advisable to have one, but in this case it would be an empty function with no arguments that does nothing, so we can just leave it and the compiler will auto-generate it.
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
This is an interesting function. It returns a this pointer. Therefore you can use the result of the function to do another call, allowing you to 'chain' multiple function calls together, like resolver.where(query).matches(filter).count().
To understand how that works requires you to understand both the class-object difference and what exactly the this pointer does.
The short version is that the this pointer is the pointer to the object that our function currently lives in.
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
This is almost the same as the where function.
The interesting part is the new Filter(...). This creates the previously discussed Filter-object from the class description and puts it in the QueryResolver object's this.filter variable.
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
Iterates through the object's query variable and checks for every letter if it is contained in filter. It keeps count of how many times this happens and returns the count.
This function requires that filter and query are set. Therefore it is important that before someone calls count(), they previously call where(..) and matches(..).
In our case, all of that happens in one line, resolver.where(query).matches(filter).count().
The main function
I wrote two different main functions. You want to test your code as much as possible during development, therefore the first one I wrote was a fixed one, where you don't have to enter something manually, just click run and it works:
public static void main(String[] args) {
String filter="kjasd";
String query="kjg4t";
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println(count);
}
Once you understand the class-object difference, this should be straight forward.
But to repeat:
QueryResolver resolver = new QueryResolver();
This creates your QueryResolver object and stores it in the variable resolver.
int count = resolver.where(query).matches(filter).count();
Then, this line uses the resolver object to first call where, matches, and finally count. Again, this chaining only works because we return this in the where and matches functions.
Now finally the interactive version that you created:
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
in.close();
}
So I've been fiddling with this problem for the past hour. I keep getting unexpected type error. It appears to be from a confliction between charAt and s.length. Any ideas on what could fix that?
class lab7
{
public static void main(String[] args)
{
String s = ("BCA");
}
public static String recursion(String s)
{
if (s.length()>=0)
{
if(s.charAt(s.length()) = A)
{
count++;
}
s.substring(0, s.length()-1);
}
return count;
}
}
There are several issues with this code, including some significant logic errors. However, the specific error you're getting is probably here:
if(s.charAt(s.length()) = A)
First, note that you're using = instead of ==, which does an assignment rather than a comparison. Also note that A should be in single quotes to be a character literal. Right now, Java thinks A is the name of a variable, which isn't defined. Finally, note that strings are zero-indexed, so looking up the character at position s.length() will give you a bounds error.
I hope this helps you get started! As a hint, although your function is named "recursion," does it actually use recursion?
Following code uses String class. For performance critical applications you might want to use StringBuffer / StringBuilder class accordingly.
class StringCounter
{
public static void main (String[] args)
{
int count = returnCount("ABCDABCDABCD", 0);
System.out.println(count);
}
public static int returnCount(String s, int count)
{
// You may want to do some validations here.
if(s.length()==0)
{
return count;
}
if(s.charAt(0)=='A')
{
return returnCount(s.substring(1), count+1);
}
else
{
return returnCount(s.substring(1), count);
}
}
}
The code simply slices the String parameter one character at a time and checks for the required character. Further on every invoke it will update the count and String parameter.
Any ideas on what could fix that?
Your function is not recursive. Recursive functions call themselves with manipulated/updated parameters.
As a thumb rule in recursive functions, always think in terms of manipulating function parameters.
Always have a base case that will terminate recursive calls.
Consider this snippet:
static int countA(String str) {
if (str == null || str.length() == 0) { /* nothing or "" contains 0 A's */
return 0;
}
return (str.charAt(0) == 'A' ? 1 : 0 ) /* 0 or 1 A's in first character */
+ countA(str.substring(1)); /* plus no. of A's in the rest */
}
And you call the function like this:
int a = countA("ABAABA"); /* a is 4 */
I realize now that this question was school related, but at least this snippet works as an exercise in understanding recursion.
public static String convertPNumber(String p) {
String b;
for (int i = 0; i < p.length(); i++) {
char a = p.charAt(i);
if (!Character.isDigit(a)) {
if (a == 'A' || a == 'B' || a == 'C') {
b = "2";
}
} else {
b = a;
}
}
return b;
}
public static void main(String args[]) {
convertPNumber("AB2");
}
I want it to print the digit if the character is a digit, but since the method is public static String, it says String is required when b = a; and it found char.
b is a type of String. a is a type of char. You cannot assign a primitive such as char to a String.
What you can do is use Character.toString(char value) instead:
b = Character.toString(a);
I'm also noticing that you've got a few deficiencies in your program...but I'll leave the major logic issue for you to fix.
When you go to fix the above issue, there is a chance that the for statement is not executed, so the variable b may not be initialized. You can fix this by initializing b to null.
Your logic is unusual - you only ever pay attention to the last character in your String, and I'm not entirely sure that's what you want. Figured I'd point that out for you.
You are taking each character in your string, and converting it into another character. But, you don't put those characters together at all. One way to do this, but not necessarily the most efficient, is to use the StringBuilder class. That class is designed to be a mutable String.
I won't write the innermost method, but here's a start.
public class ABTranslator {
public String translate(String before) {
StringBuilder b = new StringBuilder();
for (int i = 0, length = before.length(); i < length; i++) {
char a = before.charAt(i);
b.append(convert(a));
}
return b.toString();
}
public char convert(char before) {
// You write this.
}
}
You can use regular expressions instead of your if code above.
Now, write a set of JUnit tests to check whether your methods are correct:
//In ABTranslatorTest.java
#Before
public void initTranslator() {
this.translator = new ABTranslator();
}
#Test
public void digitsAreConvertedToThemselves() {
Assert.assertEquals('3', translator.convert('3');
}
#Test
public void mostCharsAreConvertedToThemselves() {
Assert.assertEquals('X', translator.convert('X');
}
#Test
public void ABCAreConvertedToTwo() {
Assert.assertEquals('B', translator.convert('2');
}
#Test
public void WordsAreConvertedAsCharactersAre() {
Assert.assertEquals("222", translator.translate("AB2");
}
Make all of these work. Find out from your colleagues how to set up JUnit 4.11. Note that I made all the methods non-static. If you don't have experience with that, write a main method. Still, that should be your only static method.
I was told in my class that I have to write and test my code in the main method, I wrote it, but I dont know how to test it. How I am supposed to test my methods? I am supposed to take user input, and then get the get the first letter, last letter, etc.
import java.util.Scanner;
public class Word
{
public static void main(String[] args)
{
}
public String word;
public void Word()
{
String word = "";
}
public void Word(String word1)
{
String word = word1;
}
public String getWord()
{
return word;
}
public void setWord(String newWord)
{
String word = newWord;
}
public void getFirstLetter()
{
String firstLetter = word.substring(0, 1);
}
public void getLastLetter()
{
String lastLetter = word.substring(word.length() - 1, word.length());
}
public void removeFirstLetter()
{
String noFirstLetter = word.substring(1, word.length());
}
public void removeLastLetter()
{
String noLastLetter = word.substring(0, word.length() - 1);
}
public int findLetter (String parameter)
{
word.indexOf(parameter);
return 1;
}
}
You test your methods by calling them with some defined input and compare the results with your expected output.
Example:
Suppose you have a method like this:
public static int add(int a, int b) {
return a + b;
}
You'd test it like this:
int result = add( 3, 5);
if( result != 8 ) {
//method is wrong
}
So basically you define a "contract" of what input the method gets and what the result should be (in terms of return value or other changed state). Then you check whether you get that result for your input and if so you can assume the method works correctly.
In order to be quite sure (you often can't be perfectly sure) you'd test the method several times with different types of input (as many as reasonable, to test different cases, e.g. short words, long words).
You often also test how your method handles wrong input, e.g. by passing null or empty strings.
You should have a look at tools like junit.
You can create a simple Test class and test your class and its behavior.
imports ...;
public class MyTest{
#Test
public void testMyClass(){
Word w= new Word();
w.setWord("test");
Assert.assertEquals(w.getFirstLetter(), "t");
}
}
With tools like Eclipse you could nicely run such a test.
Just a hint: you're very close you need an instance of Word, than you can call your methods
public static void main(String[] args) {
Word test = new Word();
test.setWord("something");
// here you might read javadoc of the String class on how to compare strings
}
EDIT:
I overlooked this:
public void setWord(String newWord)
{
String word = newWord;
}
The code you've written creates a variable word and newWord is assigned to it and then disappears.
If you (obviously) want to set a member of a class you should use this wich references the instance (you created in main()).
public void setWord(String newWord) {
this.word = newWord;
}
Since I would say this is homework, I will try not to explicitly give the answer. In the main method, you should set your word, then call each method and print the output to verify it is correct.
Agree with Jason. If you wanna test something, simply System.out.println() it. In your methods though, your return type is not a String but a void, so you could change that, and print it out on the main program run.
If not, just put the System.out.println() in your void methods. Shouldn't have much of a problem!
Im new to the java programming language and need help writing a class Anagrams that prints the permutations of words in a sentence. Example: red car -> red car, car red. This is what i have written so far and i think im on the right track and even though my code is not finished, i would at least like to get it to run.
import javax.swing.JOptionPane;
public class Anagrams
{
private String x;
private char[] xarray;
private String[] words;
public void Anagrams(String phrase1)
{
x = phrase1;
}
public void printPerms()
{
int perms = 0;
xarray = x.toCharArray();
for (int i = 0; i < x.length(); i++)
{
if(xarray[i] == ' ') perms = perms + 1;
}
words = x.split(" ");
for (int i = 0; i < perms; i++)
{
System.out.println(words[i]);
}
}
public void main(String args[])
{
String phrase1 = JOptionPane.showInputDialog("Enter phrase 1.");
Anagrams(phrase1);
printPerms();
}
}
This is the error i get when i try to run.
Exception in thread "main" java.lang.NoSuchMethodError: main
Right now im just trying to get my program to run not print out the permutations. I think i can figure that out once it at least print something out. Can someone tell me why it doesnt run and how do you get input from the user like c++ cin>>, if there is another way other than JOptionPane.
Thanks
A main method needs to be static.
How about this:
public static void main(String args[])
{
String phrase1 = JOptionPane.showInputDialog("Enter phrase 1.");
new Anagrams(phrase1).printPerms();
}
Even After Declaring your main method as static you may or may not be required to make all other methods as static(If calling methods dirctly without use of objects make methods as static).Because a static method can call or use only static data memebers or methods.
And in your code because you have defined all the methods in the same class which contains main method you need to make other methods also as static.
The method should return true if the two arguments are anagrams of each other, false if they are not.
For example, anagram(“glob”, “blog”) would return true;and anagram(“glob”, “blag”) false.
Assumes that the input strings will contain only letters and spaces. Treat upper- and lower-case letters as identical, and ignore spaces.
<br/> Uses the following algorithm:
<ul> <li> clean input strings from spaces and convert to lower case
</li> <li>convert to char array and sort them
</li> <li>if sorted arrays are identical, words are anagrams
</li></ul>
*/
public static boolean anagram(String str1, String str2)
{
//handle nulls
if(str1==null && str2==null)
return true;
else if( (str1==null && str2!=null) || (str2==null && str1!=null) )
return false;
//clean input strings from spaces and convert to lower case
String s1 = str1.replace(" ", "").toLowerCase();
String s2 = str2.replace(" ", "").toLowerCase();
//convert to char array and sort them
char[] cArr1 = s1.toCharArray();
char[] cArr2 = s2.toCharArray();
java.util.Arrays.sort(cArr1);
java.util.Arrays.sort(cArr2);
//if sorted arrays are identical, words are anagrams
s1 = new String(cArr1);
s2 = new String(cArr2);
return s1.equals(s2);
}
public static void main(String[] args)
{
//test: anagram(“glob”, “blog”) would return true; anagram(“glob”, “blag”) false.
System.out.println("anagram(“glob”, “blog”):"+(anagram("glob", "blog")));
System.out.println("anagram(“glob”, “blag”):"+(anagram("glob", "blag")));
}
You are missing static in:
public void main(String args[])
The main method needs to be static.
Also you are calling printPerms from main directly (without an object) so it must be made static as well or call them on a Anagram class object.
You are missing the new keyword while creating the object:
Anagrams(phrase1);
printPerms();
try
new Anagrams(phrase1).printPerms();
Also there is no Anagram class constructor that takes a String. What you have is a method named Anagram as you've specified the return type.
public void Anagrams(String phrase1) {
drop the void.