I want to check the number of characters in a String method - java

I want to check that a certain number of characters in a method that inputs and returns string
public static String watsonCrick(String dna){
dna = "ATA";
int length = dna.length();
char firstCharacter = dna.charAt(0);
char secondCharacter = dnaSequence.charAt(1);
char thirdCharacer = dna.charAt(2);
}
This is my code so far but I dont know what to put as my return and I don't know how to call the method from my main method? All I need is to make sure the string "dna" has three characters in it.
The method doesn't return anything as of yet, I really just want to make sure I'm on the right track and this is how I have to restrict the number of characters in my string.
EDIT: Sorry to add one more thing but if I wanted to add a condition to the method, like let's say I already made a boolean method beforehand and wanted to check if the char firstCharacter was true according to the method how would I add it?

I don't know how to call the method from my main method?
Like this:
public static void main(String[] args) {
watsonCrick("ATA");
}
or if the watsonCrick method is in a different class, like this:
public static void main(String[] args) {
OtherClass.watsonCrick("ATA");
}
All I need is to make sure the string "dna" has three characters in it.
You can do this by putting this at the beginning of the watsonCrick method:
if (dna.length() != 3) { throw new IllegalArgumentException(); }

Assing dna variable in Main method and then write just methodName(Parameters) for calling the method in Main. i.e
String dna;
public static void main(String[] args) {
dna = "ATA";
watsonCrick(dna);
}
And if you need to make sure the string has three characters, use this;
public static String watsonCrick(String dna){
int length = dna.length();
if(length == 3) {
return "true";
}
return "false";
}
If you want you can change the return type to Boolen. (True or False)

Related

Split method creates empty elements in Java Array

I have the following String "Make Me A SandWich"
Someone decided to troll me and replace the spaces with a random number of LOL.
so now the string is "LOLMakeLOLLOLLOLMELOLALOLSandWich"
My goal is to revert this change.
I tried to create a string array with split method but this caused "empty" elements inside of the array that has a value but when I try to log it, it doesn't show anything. It's also not equal to ""
Public class MyClass{
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
String[] array = trollText.split("LOL");
if (array[1]=="")System.out.print("it's an empty string");
if (array[1]==" ")System.out.print("it's a space sign");
if (array[1]==null)System.out.print("it's equal to nothing");
if (array[1]==' '+"")System.out.print("I don't know what's that");
else System.out.print(array[1]+"<-- This is an element and it has a value");
}
}
I consider the problem solved if someone tells me what array[1] equals to.
Knowing the value will give me something to compare to when copying the elements into a new array.
When comparing two strings in java, you cannot use == operator which compares object references. You need to use array[1].equals("")
Also, if you simply want to replace all occurrences of a string, you can do following
trollText.replaceAll("LOL", " ")
Here is my solution. skipping empty or " " string and appending notEmpty values to new StringBuilder() and finally print it.
import java.util.Arrays;
public class LOL_problem {
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
StringBuilder sb = new StringBuilder();
String[] array = trollText.split("LOL");
//System.out.println(Arrays.toString(array));
for (String str : array) {
if (!str.equals("")) sb.append(str+" ");
}
System.out.println(sb.toString().trim());
}
}
We should use equals(String str) method to check if strings are equals instead of '==' which does object reference check.
To replace all the occurrence, you can use trollText.replaceAll method as below.
public class MyClass{
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
String result = trollText.replaceAll("LOL", " ");
System.out.println(result);
}
}
To compare Strings in Java, use:
String.equals("text");
This will return true if the Strings are identical and false if not.

Call boolean method statically from separate class

I have a program that takes letters for input and then sums the numeric value of each letter.
I have it so that if I input "abc", my output is "6".
I ignore uppercase letters, so if I input "abC", my output is "3".
What I want to do now, is in a separate class, make a method, which if set to true will run my main program as is, but when it is set to false, it will treat uppercase letters as lowercase, giving an input of "abC", an output of "6".
I hope this makes sense, I've tried a few different things but they all run the programm as is, ignoring uppercase.
Here is my code, I appreciate any constructive feedback.
Thanks
EDIT: I would also appreciate if you didn't downvote me for asking a question, if you don't want to help dont', seems every question I asked gets downvoted for no obvious or fair reason. I didn't want to ask for help since I knew this would happen. We all start have to somewhere!
Main method:
Scanner scan = new Scanner(System.in);
System.out.println("\nPlease enter the letters you would like to use:");
String s, t = "";
scan.next();
s = scan.next();
boolean b = Converter.caseSensitive(false, s);
scan.close();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (!t.isEmpty()) {
t += ",";
}
if (ch >= 'a' && ch <= 'z') {
int n = ch - 'a' + 1;
t += String.valueOf(n);
}
}
Second method in separate class:
public class Converter {
public static boolean caseSensitive(Boolean b, String s) {
for (char c : s.toCharArray()) {
if (Character.isLetter(c) && Character.isLowerCase(c)) {
b = s.equalsIgnoreCase(s);
return false;
}
}
s = s.toLowerCase();
return true;
}
}
I believe your question is "how do I record a static boolean value in a class and then request it from another class?"
public class Configuration {
private static boolean convertToUppercase = true;
public static void setConvertToUppercase(boolean convert) {
convertToUppercase = convert;
}
public static boolean getConvertToUppercase() {
return convertToUppercase;
}
}
This can be used as:
StringConverter.caseSensitive(Configuration.getConvertToUppercase(), input);
Note that most coders (me included) would consider this poor design but explaining why is outside the scope of your question.
There are a lot of other issues with your code. For example your method call above will leave the input string unchanged. But I suggest you ask another question with just the relevant code when you get stuck.
String is immutable in Java. Please read following stackoverflow question for more information about this topic:
String is immutable. What exactly is the meaning?
public static void main(String[] args) throws Exception
{
String test = "abc";
toUpperCase(test);
System.out.println(test);
}
private static void toUpperCase(String test)
{
test = test.toUpperCase();
}
Please note that above code will output:
abc
In order to have "ABC" as result you need to use following code:
public static void main(String[] args) throws Exception
{
String test = "abc";
test = toUpperCase(test);
System.out.println(test);
}
private static String toUpperCase(String test)
{
return test.toUpperCase();
}
This one outputs:
ABC
So your Converter.caseSensitive method should return String.
I don't think you really need the Converter class. You can delete class and replace the line:
boolean b = Converter.caseSensitive(false, s);
with this
boolean shouldCountUppercaseLetters = false;
if (shouldCountUppercaseLetters) {
s = s.toLowerCase();
}

Making a program into two different classes

So I had to write a code that takes a word and reverse it I got it to work but for my homework I had to make it into two classes a tester class and a main class how do I do that?
public static void main(String args[])
{
String original = "";
String reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
{
reverse = reverse + original.charAt(i);
}
System.out.println("Reverse of entered string is: "+reverse);
}
You create two classes. You can even put a main method in both of them.
public class Homework {
public static void main(String[] args) {
// Code here to prompt user for string and to print reversed string
}
static String reverse(String input) {
// Code here to do the actual reverse logic, returning reversed string
}
}
public class HomeworkTest {
public static void main(String[] args) {
test("Hello", "olleH");
test("This is a test", "tset a si sihT");
}
private static void test(String input, String expected) {
String rev = Homework.reverse(input);
System.out.println(input + ": " + rev);
if (! expected.equals(rev))
System.out.println(" ** NOT AS EXPECTED: " + expected);
}
}
You can now run the Homework for manual testing, or the HomeworkTest class for automatic testing.
You could get the original String in the Main-class and hand it to the second class to execute the for-loop. The second class then returns the reversed String so that the Main-Class can print it out.
The second class could contain a static method which reverses the String (executes the for-loop) or you can create an object of the second class and and this Object the original String to reverse.
There are several ways to do this. Most trivially, you could make a static function in a Test class, like so:
class Test
{
public static void runTest(String args[])
{
//same as your above program
}
}
But that is probably not what your teacher wants. Instead, you could make a Test class that reverses a set of strings.
class Test
{
public static void runTests()
{
//iterate through a list of hard-coded strings to test
}
}
You would then make a separate function in a Reverser class and the Test.runTests() function would test the Reverser class.
However, there are standardized ways of doing this. One common way is called JUnit. If you are using Eclipse, try this page for instructions.
The simplest way is to
Divide your code into a function public String reverse(String input)
Create new Tester class
Add test method in tester class public void test()
Prepare assertions to test your function assert reverse("ola").equals("alo") : "First assertion failed"
In main function run new Tester().test();
To make assertions working you have to run jvm with -ea option

How to use boolean statements and return

I am trying to create a piece of code which will;
return true if given an int n, which is with in 10 of 100 or 200.
import java.util.Scanner;
class nearHundred{
public boolean nearHundred(int n){
Scanner input = new Scanner(System.in);
n = input.nextInt();
if(10>=Math.abs(100-n) || 10>=Math.abs(200-n)){
return true;
}
return false;
}
}
Where have I gone wrong?
From comments it looks like your main method is misplaced, wherever it is I hope it exists only once in a project. Call your class from that main() method, for example -
new nearHundred().nearHundred(100); // a call from main method
Now coming to your code there are several things to correct here. Your method should not take care about Scanner, its job is to take input and check for the logic.
For example;
public class Utils {
public static boolean isNearToHundered(int num) {
return Math.abs(num-100)<=10 || Math.abs(num-200)<=10;
}
}
Give the responsibility to main method for parsing the input, this is how it should work.
Now since I made method static, you can call like
Utils.isNearToHundred(105); // TRUE
Here is how the method should look:
public void mainMethod() {
Scanner input=new Scanner(System.in);
int val=input.nextInt();
boolean nearHundredBoolean=nearHundred(val);
//do something with nearHundredBoolean....
//Same logic, but passes the input to the method nearHundred
public boolean nearHundred(int n) {
if(Math.abs(100-n)<=10 || Math.abs(200-n)<=10)
return true;
else return false;
}
You should pass the value of the scanner input into this method's parameter requirement, instead of not using the parameter n in your current method. If there is a problem, it may be due to the 'input.nextInt()' method that overwrites the value of the parameter n.

Java String function can not be called because it's not static

Let me explain further. I have a String function (called stringReversal) that returns a reversed string, it has no errors in the function. But, when I try to print using System.out.println() from the main function, it gives me the error "Can not make a static reference to the non static method stringReversal (string s) from the type StringReverse".
I tried giving my stringReversal a static modifier, but after doing so, it gave me run time errors.
Here's what my code looks like:
public class StringReverse {
public String stringReversal(String s){
if(s == null){
return null;
}
else if(s.length()% 2 == 0){
int size = s.length();
for(int i =0; i<s.length(); i++){
s.replace(s.charAt(i), s.charAt(size));
size--;
if(i == (s.length()/2) || size==0)
break;
}
}
else{
for(int i =0; i<s.length(); i++){
int size = s.length();
s.replace(s.charAt(i), s.charAt(size));
size--;
if(i == ((s.length()/2) +1) || size==0 )
break;
}
}
return s;
}
public static void main(String[] args) {
String str = "Hello";
String rev = stringReversal(str);
System.out.println();
}
}
You have to instantiate your class to call object members, or you need to make your function static, indicating it's not part of object oriented paradigm
In your case you can do
StringReverse sr = new StringReverse();
String rev = sr.stringReversal("hello");
or declare your method differently
public static String stringReversal(String s)
In fact the class name StringReverse itself does not sound like some kind of object, so the second way is preferred impo
The deeper problem you have is the confusion on how Java handle OO and entrance function in general. Java is primarily an OO language so most of the time everything shall be an object or a member of a object. But when you telling the VM to run some java code, there got to be a place to start, which is the main method. There has to be one main method and it must be under some class, but it really has nothing to do with the class that contains it. Within the main method, you either start your OO life by instantiating objects and invoking their members (method 1) or stay in the spaghetti world for a bit longer, by calling other static members as procedures (method 2).
You have two options:
Keep the method non static and then create an instance of your class to call the method:
public static void main(String[] args) {
String str = "Hello";
StringReverse sr = new StringReverse(); // instance of class
String rev = sr.stringReversal(str);
System.out.println(); // just prints a blank line lol...
}
Make the method static (you should do this):
public static String stringReversal(String s) {
// ...
}
public static void main(String[] args) {
String str = "Hello";
String rev = stringReversal(str);
System.out.println(); // just prints a blank line lol...
}
Either way, you have to fix your "run time errors". You can't get around that. If your method doesn't work, keeping it not static won't make it work either.
By the way, I think you meant to do System.out.println(rev); instead of System.out.println();
For the record, here is how to easily reverse a string (both methods work):
public static String stringReversal(String s) {
StringBuffer reverseString = new StringBuffer();
// reverse the string
for (int i = s.length() - 1; i > -1; i--) {
reverseString.append(s.charAt(i));
}
return reverseString.toString();
}
/* using the reverse() method in the StringBuffer class
instead of reversing the string through iterations */
public static String stringReversal2(String s) {
return new StringBuffer(s).reverse().toString();
}
This is happening because your Main method is static, but the class that it's in is not. In order to call a non-static method, you need to create an instance of the class. Alternatively, the method can be made static, but in order to refer to it you need to include the class name in your call (as if to use the class itself like an object containing the method - see below).
There are three solutions to this problem:
Make an instance of the class and call the method from your object (recommended).
make the method static and use StringReverse.stringReversal().
Make the class AND the method static.

Categories

Resources