I wish to return a string from a method object that is called by another method in another class. My problem is: when I attempt to assign the returned value to a String in the other class, it cannot find the method object within the class object.
Guessing Game = new Guessing();
This makes the object using the class Guessing.Java
else if (buttonObj == guess){
double g = yourGuess.getNumber();
if ((g > 0)&&(g < 11)){
Game.StartGame(g);
label3.setVisible(false);
yourGuess.setEnabled(false);
label1.setText(Game.StartGame());
}else{
label3.setVisible(true);
yourGuess.requestFocus(true);
}
}
When I try retrieving the String from the StartGame method within the Guessing.Java class, it says it cannot find the class.
public String StartGame(double guess){
int round = 1;
int guesses = 3;
String correct = "correct";
if (guesses > 0){
if (guess == ans){
correct = "correct";
}else if ((guess == ans - 1)||(guess == ans + 1)){
correct = "hot";
guesses--;
}else if ((guess == ans - 2)||(guess == ans - 2)){
correct = "warm";
guesses--;
}else{
correct = "cold";
guesses--;
}
}else{
correct = "round";
}
return correct;
}
I have tried several different things and looked it up multiple times but nothing works, can anyone help?
First of all fix your code by using these Naming Conventions.
Change your code to this,
if (buttonObj == guess){
double g = yourGuess.getNumber();
if ((g > 0)&&(g < 11)){
String startGameStr = Game.StartGame(g);
label3.setVisible(false);
yourGuess.setEnabled(false);
label1.setText(startGameStr);
}else{
label3.setVisible(true);
yourGuess.requestFocus(true);
}
}
It is hard to tell what is causing the "class not found" exception with the details given.
But one thing I could see it : You are calling the method as:
label1.setText(Game.StartGame());
But the method expects a double argument.
according to the first code segment there two overloaded methods in Guessing class
StartGame(Double g)
StartGame()
seems to be like you are calling the second method when you try to assing the returned string to that label which probably retuning emty string or since that method doesn't exist you get method not found exception.
Related
Problem:
Remove the substring t from a string s, repeatedly and print the number of steps involved to do the same.
Explanation/Working:
For Example: t = ab, s = aabb. In the first step, we check if t is
contained within s. Here, t is contained in the middle i.e. a(ab)b.
So, we will remove it and the resultant will be ab and increment the
count value by 1. We again check if t is contained within s. Now, t is
equal to s i.e. (ab). So, we remove that from s and increment the
count. So, since t is no more contained in s, we stop and print the
count value, which is 2 in this case.
So, here's what I have tried:
Code 1:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting "Wrong Answer" for rest of the cases). After a while, I found out that there is something called replace() method in Java. So, I tried using that by replacing the if condition and came up with a second version of code.
Code 2:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
But for some reason (I don't know why), the "Marked Statement" in the above code gets executed infinitely (this I noticed when I replaced the "Marked Statement" with System.out.println(s.replace(t,""));). I don't the reason for the same.
Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a "Wrong Answer". How do I overcome that if I use Code 1? And if I use Code 2, how do I avoid infinite execution of the "Marked Statement"? Or is there anyone who would like to suggest me a Code 3?
Thank you in advance :)
Try saving the new (returned) string instead of ignoring it.
s = s.replace(t,"");
replace returns a new string; you seemed to think that it alters the given string in-place.
Try adding some simple parameter checks of the strings. The strings shouldn't be equal to null and they should have a length greater than 0 to allow for counts greater than 0.
static int maxMoves(String s, String t) {
int count = 0,i;
if(s == null || s.length() == 0 || t == null || t.length() == 0)
return 0;
while(true)
{
if(s.contains(t) && !s.equals(""))
s = s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
You might be missing on the edge cases in the code 1.
In code 2, you are not storing the new string formed after the replace function.
The replace function replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
Try this out:
public static int findCount(String s, String t){
if( null == s || "" == s || null == t || "" == t)
return 0;
int count =0;
while(true){
if(s.contains(t)){
count++;
int i = s.indexOf(t);
s = s.substring(0, i)+s.substring(i+t.length(), s.length());
// s = s.replace(t,"");
}
else
break;
}
return count;
}
String r1="ramraviraravivimravi";
String r2="ravi";
int count=0,i;
while(r1.contains(r2))
{
count++;
i=r1.indexOf(r2);
StringBuilder s1=new StringBuilder(r1);
s1.delete(i,i+r2.length());
System.out.println(s1.toString());
r1=s1.toString();
}
System.out.println(count);
First of all no logical difference in both the codes.
All the mentioned answers are to rectify the error of code 2 but none told how to pass all (14/14) cases.
Here I am mentioning a test case where your code will fail.
s = "abcabcabab";
t = "abcab"
Your answer 1
Expected answer 2
According to your code:
In 1st step, removig t from index 0 of s,
s will reduce to "cabab", so the count will be 1 only.
But actual answer should be 2
I first step, remove t from index 3 of s,
s will reduced to "abcab", count = 1.
In 2nd step removing t from index 0,
s will reduced to "", count = 2.
So answer would be 2.
If anyone know how to handle such cases, please let me know.
I am using BlueJ IDE to write java programs.
I have a method with String return type. I have put the return statements within if-else, such that if the boolean variable "flag" has true value, then one value is returned, while if the value is false, another value is returned.
Now, the problem is that BlueJ asks for another return statement even after this, as shown below.
If I give another return after if-else, it works.
Why is this happening? I had learnt that there can be no statements after the return statement. So, why is the compiler asking for another return statement?
If someone wants the code for cut-paste purposes, here it is. This code is meant to convert binary numbers to their decimal equivalents, including fractions, but no negative numbers.
public class Conversions{
protected String Binary_Decimal(String str){
int a = str.indexOf('.');
boolean flag = false;
if (a == -1){
str += ".0";
a = str.indexOf('.');
flag = true;
}
String bd = str.substring(0, a);
String ad = str.substring(a + 1);
a = 0;
double num = 0;
for (int i = bd.length() - 1; i >= 0; i--){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a++;
}
if (flag == true){
return Integer.toString((int) num);
}
else if (flag == true) {
a = -1;
for (int i = 0; i < ad.length(); i++){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a--;
}
return String.valueOf(num);
}
return String.valueOf(num); //<-- WHY DOESN'T IT RUN WITHOUT THIS EXTRA return?
}
}
Here, str is the string that is input by the user using a different method Input().
The issue is that you wrote an if - else as an if - else if. The compiler does not understand or care that the two conditions you have are mutually exclusive and therefore cover all cases. Given how you wrote the branches, you need an explicit else or a catchall return for the compiler to be assured that the function always returns a String.
This is one example of why it is a bad idea to explicitly spell out the else when you have a set of conditions. The more important reason being that your if will often contain something much more complex and you might not negate it properly.
Delete the second ELSE IF clause and put the block directly after the first return statement, and consider that flag is a boolean. As follows:
if (flag) return Integer.toString((int) num);
a=-1;
for(....){
....
}
return String.valueOf(num);
In this way, the compiler should not notify you that error.
So, why is the compiler asking for another return statement?
Because you are missing a default return statement.
What if none of the conditions you have satisfied ? There must be something return default right ? That is what the issue is. That is why it is getting compiled when you uncomment that line.
Or even , you have an else statement, your program will have at least one satisfied return and it gets compiled too. Try it.
I had learnt that there can be no statements after the return statement.
This statement comes with some conditions. You have the return statement inside the if condition. So if your expression is not true, there is no way that the return gets execute.
So i'm writing a little program to practice for my exam coming up, and it involves creating a class file as well as an application file. Basically, i'm not sure if my setup will work because user input is required from the Scanner class, and i'm not aware of a method for Strings similar to, say, the nextInt() or nextDouble() methods. Here is a snippet of what I have written so far, and I was basically wondering how I could make the set methods i'm using work when I need to take user input(some of my set methods use Strings and not primitive data types like an int or double). Just curious if my current format can work once I get around to the application class, or if I need to change my methods to use a numerical input instead of Strings and then use something like a switch or if statement later on to change those numerical values to a String. Here is what i've written so far, from the class file:
import java.text.DecimalFormat;
public class GuitarStore
{
DecimalFormat dollar = new DecimalFormat("$#,##0.00");
private int stockNumber;
private int modelID;
private int pickupType;
private String color;
private String brand;
private String pickupType
private double totalValueOfStock;
public GuitarStore()
{
stockNumber = 0;
modelID = 0;
pickupID = 0;
color = "";
brand = "";
pickupType = "";
totalValueOfStock = 0.0;
}
public GuitarStore(int stkNum, int modID, int pickID, String clor, String brnd,
double totValOfStock)
{
setStock(stkNum);
setModel(modID);
setPickup(pickID);
setColor(clor);
setBrand(brnd);
setTotalValue(totValOfStock);
}
public void setStock(stkNum)
{
if (stkNum > 1 && stkNum <= 500)
{
stockNumber = stkNum;
}
else
{
stockNumber = 0;
}
}
public void setModel(modID)
{
if (modID >= 1 && modID <= 1000)
{
modelID = modID;
}
else
{
modelID = 0;
}
}
public void setPickup(pickID)
{
if (pickID > 1 && pickID <= 3)
{
pickupID = pickID;
}
else
{
pickupID = 0;
}
}
public void setColor(clor)
{
if (clor == "red")
color = clor;
else if (clor == "blue")
color = clor;
else if (clor == "purple")
color = clor;
else if (clor == "green")
color = clor;
else if (clor == "white")
color = clor;
else
System.out.println("We do not carry that color");
Basically, i'm most curious about the setColor method and if/how it will work once I get to the application part of the program. In previous projects, i've just used numbers and not strings which I then converted to a string using a switch statement. This is something totally new to me and i'm going out on a limb trying something new. Since I need to take user input to determine what color they will want, i'm not sure how to parse that since I can't use a method like nextDouble() or nextInt() like I stated above. This is total practice so if anyone can tell me if I have a solid plan or not i'd appreciate it, and also what I should do to take the user input once I get to the application process for the set methods. Thanks, everyone here is always so helpful!!! :)
Scanner does have a next method, which reads a token regardless of type and returns it as a String, as well as a nextLine method, which does what you expect. In general, I would suggest using next or nextLine over nextInt and other type-specific methods, just because you may run into some unexpected behaviour if the input isn't exactly right.
Also, you shouldn't compare two strings with the == operator. In Java, == is a reference (or shallow) comparison, which essentially checks if two objects are stored in the same place on your computer; this works for primitive types (ints, doubles, etc.), because of how they're represented in the language. It will NOT work for Strings, because Strings are complex objects in Java. Instead you should use the equals method, which will do a deep comparison - checking if all of the data is identical.
Here's what I'm trying to implement:
"If the strand is:
AACATGTACTACTGGTG
and the snip method is called like this:
snip("CA", "A")
then the resulting new DNAStrandJedi object should represent the
strand "TGT" which is found after the first match of "CA" at index 2
and before the subsequent match of "A" at index 7."
And here's my code:
public DNAStrandJedi snip(String startPattern, String endPattern) {
if (!passedStrand.contains(startPattern)
|| !passedStrand.contains(endPattern)) {
return null;
} else {
String snippedString = passedStrand.substring(3, 5);
return new DNAStrandJedi(snippedString);
}
}
The strand that I'm trying to snip is: "AGTCAGTACC"
Here I'm printing the results of the snip() method to the console:
System.out.println("Snip: " + test.snip("GT", "TA").getStrandString());
I should be getting the strand "CAG" but instead I'm just getting CA.
What I'm having trouble with is figuring out the numbers to use as indices to get the snippedString. Would I have to use some sort of for loop here to get the indices of the startPattern and endPattern? Let me know if you find the question confusing and I'll try to explain it better.
The String.indexOf() function is what you need.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String, int)
if (passedStrand.indexOf(startPattern) > -1 && passedString.indexOf(endPattern, passedStrand.indexOf(startPattern)) > -1)
return return new DNAStrandJedi(passedStrand.indexOf(startPattern)+startPattern.length, passedString.indexOf(endPattern, passedStrand.indexOf(startPattern))-1);
else
return null;
(not tested and not optimal, but its something similar)
The code below is written in simple and clear way and it might explain
public DNAStrandJedi snip(String startPattern, String endPattern) {
int sL = startPattern.length();
int startIndex = passedStrand.indexOf(startPattern);
int endIndex = passedStrand.indexOf(endPattern, startIndex + sL);
if ( startIndex == -1 || endIndex == -1 )
return null;
}
String snippedString = passedStrand.substring(startIndex+sL, endIndex);
return new DNAStrandJedi(snippedString);
}
For the information of Java String Functions you can see at here
Actually #vanza appears to have answered your question it's the "substring(3,5)" that is hard coded that is causing the problem.
You reference a "passedStrand" variable, but you don't show how it is initialized...Did you maybe miss something that's related that we need to know to help you solve the problem?
Use indexOf to find the indices...
} else {
int start = passedStrand.indexOf(startPattern) + startPattern.length();
int end = passedStrand.indexOf(endPattern, start);
String snippedString = passedStrand.substring(start,end);
return new DNAStrandJedi(snippedString);
}
I make chessboard, where alone king will walk according to the rules of chess.
Below it's method to make, it called for 2 times for i and j coordinate of King, I Made input variable String to check if this King's coordinates already exist. Than I try to convert it to integer, seems something wrong with this conversion.
import java.util.*;
public class King {
int move(String iK){
Random rand = new Random();
Integer coordinateKing = Integer.valueOf(iK);
if (iK == null){
coordinateKing = rand.nextInt(8);
}else{
int caseI;
switch(caseI = rand.nextInt(2)){
case 0: if (coordinateKing < 8){ coordinateKing++; } else {caseI = rand.nextInt(2);}
break;
case 1: if (coordinateKing > 0){ coordinateKing--; } else {caseI = rand.nextInt(2);}
break;
default:
break;
}
}
return coordinateKing;
}
}
I have problem like this:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.valueOf(Integer.java:582)
at chess_engine.King.move(King.java:6)
at chess_engine.MainClass.main(MainClass.java:12)
Thanks in advance!
You're attempting to convert iK to an integer before you check to see if it's null. This line is where the exception is thrown:
Integer coordinateKing = Integer.valueOf(iK);
But you check if (iK == null) on the line following that. You should do a null test first. You can fix this by declaring coordinateKing before your if statement and setting its value in the if...else blocks.
Integer coordinateKing = 0;
if (iK == null){
coordinateKing = rand.nextInt(8);
} else {
coordinateKing = Integer.valueOf(iK);
int caseI;
...
}
You call this
Integer coordinateKing = Integer.valueOf(iK);
but iK can be NULL there. do your null check first
The exception is pretty self-explanatory. iK is a null String, which can't be converted to an Integer. What Integer do you want when iK is null?
It is a runtime error: here the iK is receiving a null value and an Integer object can store null but the method valueOf() internally uses the parseInt() method which returns an int value and a null cannot be converted to int