Mixing different types - java

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;

Related

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

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.

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)

Bool vals won't print out in console

I am interested in a very simple string verification problem to see if the starting character in a string starts with an upper case letter and then have the console to display true or false. From my understanding you wouldn't have to invoke something like System.console().printf("true", s) in order to make this happen. I could swear I've seen similar elementary implementations achieved using the following sample code:
public class Verify {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
but when I run this, nothing displays. If I make a slight modification by adding in conditional printouts before returning T/F, e.g.
public class Verify2 {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
System.out.println("yep");
return true;
}
else {
System.out.println("nope");
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
the issue is somewhat resolved, as the console displays either "yep" or "nope", yet unresolved because I just want the console to display true or false. That's it. Advice?
As the question has already been answered, I'd like to point out there is no need for RegExes to solve this (and they are expensive operations). You could do it simply like this:
static boolean startsWithUpperCase(String toCheck)
{
if(toCheck != null && !toCheck.isEmpty())
{
return Character.isUpperCase(toCheck.charAt(0));
}
return false;
}
yet unresolved because I just want the console to display true or false
Calling checkStartChar method will return value, that doesn't mean it will print value to console. You need to code how you would like to handle return value. If you want to print return value, then you should do:
System.out.println(checkStartChar(str));
Will print what ever the return of checkStartChar method
if(s.startsWith("[A-Z]")){
String.startsWith(prefix) doesn't take regex as a parameter, you should be using regex APi instead.
Pattern p = Pattern.compile("[A-Z]");
Matcher m = p.matcher(new Character(s.charAt(0)).toString());
if(m.find()){
return true;
}else{
return false;
}
String str = "AbCD";
System.out.println(checkStartChar(str));
Output:
true
In your code checkStartChar(str); is returning a boolean value which is not being used in your program.Then if you want to display true or false then you can use.
System.out.println(checkStartChar(str));

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