Call boolean method statically from separate class - java

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();
}

Related

Eclipse JAVA String reverse - reversing 1 word which is pre-declared [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 5 years ago.
Like to know how to reverse a string value (1 word) which is pre-declared in the program. I mean not using user input or scanner.
Like to reverse a word "TRAIN" which is pre-declared in the program.
Have tried the below program but no results and no error also.
// QUERY PROGRAM NOT RUNNING - NO RESULT, NO ERROR.
// STRING REVERSE PROGRAM USING ARRAY
package abnpackage;
class Play {
void REVERSE (){
String [] INPUT_WORD = {"T","R","A","I","N"};
int Q;
for(Q=INPUT_WORD.length-1; Q>=0; Q=Q--);
System.out.print ("REVERSE VALUE" + INPUT_WORD[Q]);
}
public static void main(String[]args){
Play PL = new Play();
PL.REVERSE();
}
}
Problem in Q=Q-- and ; symbol after for cylce. Try this:
class Play{
void REVERSE (){
String [] INPUT_WORD = {"T","R","A","I","N"};
int Q;
for(Q=INPUT_WORD.length-1; Q>=0; Q--) {
System.out.print(INPUT_WORD[Q]);
}
}
public static void main(String[]args){
Play PL = new Play();
PL.REVERSE();
}
}
I'd like to offer a few suggestions.
Indent your code. It not only makes it easier for you to follow, but makes it easier for others to read your code.
Naming conventions. Use Title case for classes, camelCase for both variables and methods, and UPPER_CASE for constants.
Strings and characters. A String can be decomposed into an array of characters with the built-in method, String.toCharArray(). A character array is mutable, so is often used as an intermediate structure when converting a String from one state to another for tasks like ciphers or interview problems.
Encapsulation. If you can make your methods use only what is submitted to them through their method signature, and only output their return value, it's usually best. Prefer passing values over referencing constants in your utility methods to make them easier to follow.
package abnpackage;
class Play {
private static final String INPUT_WORD = "TRAIN";
private String reverse(String word) {
char[] letters=word.toCharArray();
StringBuilder sb=new StringBuilder();
for (int q=letters.length-1; q>=0; q--) {
sb.append(letters[q]);
}
return sb.toString();
}
public static void main(String[]args) {
Play play = new Play();
System.out.println("REVERSE VALUE: " + play.reverse(INPUT_WORD));
}
}
class Play {
void REVERSE() {
String[] INPUT_WORD = {"T", "R", "A", "I", "N"};
String[] OUTPUT_WORD =new String[INPUT_WORD.length];
int length = INPUT_WORD.length;
int i = 0;
while(--length>=0){
OUTPUT_WORD[i++] = INPUT_WORD[length];
}
System.out.println(Arrays.toString(OUTPUT_WORD));
}
public static void main(String[] args) {
Play PL = new Play();
PL.REVERSE();
}
}
Your code is entering an endless loop because of the assignment "Q=Q--"
for(Q=INPUT_WORD.length-1; Q>=0; Q=Q--);
It should instead be
Q--
without a semicolon at the end.
If the code runs successfully, it will print the words "REVERSE VALUE" repeatedly prior to printing each character in reverse.
System.out.print ("REVERSE VALUE" + INPUT_WORD[Q]);
So you will want to keep the text in reverse prior to printing the whole statement at the end of the execution of the for loop.
What is the reason to use array of String instead of just String? Since it's not mentioned as a requirement, I'm suggesting the following as an alternative solution:
public class Play {
static void reverse(){
String inputWord = "TRAIN";
char[] toStrArray = inputWord.toCharArray();
char[] revisedInput = new char[inputWord.length()];
int i = 0;
for(int q=toStrArray.length-1; q>=0; q--){
revisedInput[i]=toStrArray[q];
i++;
}
System.out.print ("REVERSE VALUE: " + new String(revisedInput));
}
public static void main(String[]args){
//Play PL = new Play();
//PL.REVERSE();
reverse();
}
}
Note: You can declare the method reverse as a static method. By doing this you don't have to create an object before calling it. Hope this helps.

java program with methods and boolean

import java.util.Scanner ;
public class ProcessNumbers
{
public static void main( String[] args )
{
Scanner in = new Scanner(System.in) ;
System.out.print("Please enter an integer between 6 and 12, inclusive: ") ;
int num = in.nextInt() ;
boolean result = shouldProcess(num);
String result1 = String.valueOf(result) ;
}
public static boolean shouldProcess(int n)
{
if (n>=6 && n<12)
{
return true;
}
else
{
return false;
}
}
public static boolean processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
return result2 ;
}
}
now I am getting the output which is partially right but has forgot the yes or no output in the second method
Please enter an integer between 6 and 12, inclusive:
when it should also include the yes or not output
You are sending in a boolean value in the method parameter of processInput but you are catching it as a String. You need to change it to boolean. Further, you want to check if its value is true with equal signs like below:
public static void processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
}
EDIT 2:
Also, you need to change String result1 = String.valueOf(result); to processInput(result);
EDIT 3:
If you want the number printed too that you just entered and then you want a "yes" or "no", then between int num = in.nextInt(); and boolean result = shouldProcess(num);, add this line: System.out.println(num);
There's apparently some code missing, so I'm guessing this is just part of the full thing. So I will only tackle your output issue.
I won't talk about the code in: public static boolean processInput(boolean result2), because you're not running it anywhere in your main method public static void main( String[] args ) anyway.
Now, in your code at:
public static boolean shouldProcess(int n)
if you look at your code, you are assigning the value of the boolean to the new String result1, so result1 now has the new value, but you are not running its output anywhere, so there's no way the program can guess you want to output that value. You need to assign the output:
System.out.print(result1);
However, if you only want to output the boolean, there's no need to assign that boolean value to a new String and then output the new String, you could just:
System.out.print(result);
Unless you're going to use that value somewhere else where creating a new variable would arguably be a good choice.
Also, it seems you want to return either a "Yes" or "No" on your class: public static boolean processInput(boolean result2).
Remember a class that does not return a value, but rather executes a code, has to be written as void. In other words, your:
public static boolean processInput(boolean result2)
should really be:
public static void processInput(boolean result2)
Because if not, you are just making your program return result2;, which in this case can only be either true or false. By adding void to the class, makes the class understand it will be executing your System.out.print code, rather than returning a value for you to use. But also, depends on what you want to afterwards.

Mixing different types

I'm new to Java and i don't have much experience programming. I've been working with this code for a while now, and I'm not really sure how to make it work.
public class Bases {
public static void main(String[] args) {
String base = args[0];
char valid = args[0].charAt(0);
char[] newvalid = { 'A', 'G', 'C', 'T'};
if (valid == newvalid)
return valid;
else
System.out.println("Not a valid base");
}}
So here are my questions:
1. Is it possible to mix char[] and char?
2. And can someone explain why you "cannot return a value from method whose result type is void"?
Any help would be appreciate.
Mixing types is not a java concept however you can compare, which is what you are looking for. Since newvalid is an array lets loop it and see if valid is inside.
boolean contains = false;
for (char c : newvalid) {
if (c == valid) {
contains = true;
break;
}
}
if (contains) {
// do your stuff
}
cannot return a value from method whose result type is void
Means that in method with return declaration void you can not return a value, hmm maybe that's exactly what is in the message...
I will highlight your code so that you can understand
public static void main(String[] args) //This is your method, see the void as return type
.....
return valid; //Here you try to return a char and this is not allowed, since it is declared void
To solve compilation problem, change return valid; to return;

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

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)

Learning java, cannot find symbol

I'm learning Java and stuck on a self test exercise writing a recursive function that prints a string backwards...
I understand the compiler error but I'm not sure what to do about it.
My code...
class Back {
void Backwards(String s) {
if (s.length = 0) {
System.out.println();
return;
}
System.out.print(s.charAt(s.length));
s = s.substring(0, s.length-1);
Backwards(s);
}
}
class RTest {
public static void main(String args[]) {
Back b;
b.Backwards("A STRING");
}
}
Compiler output...
john#fekete:~/javadev$ javac Recur.java
Recur.java:3: error: cannot find symbol
if (s.length = 0) {
^
symbol: variable length
location: variable s of type String
Recur.java:7: error: cannot find symbol
System.out.print(s.charAt(s.length));
^
symbol: variable length
location: variable s of type String
Recur.java:8: error: cannot find symbol
s = s.substring(0, s.length-1);
^
symbol: variable length
location: variable s of type String
3 errors
Finished code...
class Back {
static void backwards(String s) {
if (s.length() == 0) {
System.out.println();
return;
}
System.out.print(s.charAt(s.length()-1));
s = s.substring(0, s.length()-1);
backwards(s);
}
}
class RTest {
public static void main(String args[]) {
Back.backwards("A STRING");
}
}
Write it like this:
s.length() == 0 // it's a method, not an attribute
Some general 'good coding' suggestions:
Class names should represent a 'thing', usually a classname is a noun (e.g. "StringTool")
Methods should represent an action, usually a methodname is a verb (e.g. "reverse")
Parameter and variable names should be meaningful and describe what they represent.
You should not re-assign method parameters because it can be misleading.
A method should have precisely one responsability (so not reversing AND printing a string). This promotes clarity and reuse.
I have applied these suggestions to your finished code, see below:
public class StringTool {
public static String reverse(String source) {
// stop condition of the recursion
if (source.isEmpty()) {
return "";
}
int lastPosition = source.length() - 1;
String lastCharacter = source.charAt(lastPosition);
String restOfSource = source.substring(0, lastPosition);
// place the last character at the beginning and reverse the rest
// of the source recursively
return lastCharacter + reverse(restOfSource);
}
// test method
public static void main(String args[]) {
System.out.println(reverse("A STRING"));
}
}
In your if statement, you are assigning 0 to s.length rather than checking. do it this way:
if(s.length()==0)
//rest of your code
another fault is s.charAt(s.length()). The index of i th character in a string is (i-1), similar to the indices of an array. So the last character of the string has index (s.length()-1). So replace that line of code with s.charAt(s.length()-1).
This should better reflect what you're trying to accomplish:
class Back {
void Backwards(String s) {
if (s.length() == 0) {
System.out.println();
return;
}
System.out.print(s.charAt(s.length()));
s = s.substring(0, s.length()-1);
Backwards(s);
}
}
public class RTest {
public static void main(String args[]) {
Back b = new Back();
b.Backwards("RAPE APE");
}
}
length() is a function
comparison uses ==
You must instantiate b to use it
You forgot the parentheses:
s.length()
length is a method, not an attribute. You'll have to use it that way:
s.length(); // note the use of parens
Also, you'll have a compilation error after fixing that, because of the following condition:
if (s.length = 0) {
It should be
if (s.length == 0) {
And finally, in your main method, the b variable will have to be instantiated, using
Back b = new Back();
- With String we are provided a function named length() and not a field length.
- If you were using an Array then it would had been length as Array has one and only one Instance variable named length.
Eg:
s.length() == 0;

Categories

Resources