Display character and integer to string with conditional in java - java

I think I'm missing something fundamental. I'm trying to display a character and an integer into a string while using a conditional.
Code:
public String display()
{
String Term = Character.toString(B) + Integer.toString(C);
int length = Term.length();
if (length == 1) {
Term = Character.toString(B);
}
if (length > 1) {
Term = Character.toString(B) + Integer.toString(C);
}
return Term;
}
public char getB()
{return B;
}
public int getC()
{return C;
}
Where B is a character and C is an integer. So the error that keeps coming up looks like this:
A.display() should return "A" expected: < A [] > but was: < A[1] >
I've been trying to fix this for hours now and to no avail. How should I go about fixing this error? Thanks.

First, this code won't run as it is because you should declare your character and integer variables.
Plus, you're getter-methods are used in case you have another interfering class with this class.
And if you want a code for such a problem don't hesitate to ask me.

Related

Java method returns int that can't be compared to another int (Android Studio)

First off, these are ints, not Integers.
I want to get a variable from another class and compare it to a value, like so:
Log.v("xx", "" + boardAdap.getPieceNumber());
int pieceNumberInt = boardAdap.pieceNumber;
if (pieceNumberInt == 32) {
Log.v("xx", "int comparison worked");
}
int pieceNumberMethod = boardAdap.getPieceNumber();
if (pieceNumberMethod == 32) {
Log.v("xx", "method comparison worked");
}
So, I want to get the pieceNumber variable from the boardAdap class, and check if it is equal to 32. If it is, it prints the stuff in Log in the console.
The boardAdap method:
int pieceNumber;
int pieceNumberIncrement;
public int getPieceNumber() {
for (int i = 0; i < 64; i++) {
if (board.getPiece(Square.squareAt(i)).name() != "NONE") {
this.pieceNumberIncrement++;
}
}
this.pieceNumber = pieceNumberIncrement;
return pieceNumber;
}
This iterates through an enum called Square, and increments pieceNumberIncrement if the value is not "NONE".
However, when I run this, the output is:
32
int comparison worked
So, why does the second if condition fail, if getPieceNumber() returns an int? It also fails when I use an Integer wrapper, or convert pieceNumberMethod to a string and then to an Integer, and other methods.
Also, should I change getPieceNumber() to just update the pieceNumber instead, and reference only that?
Additionally, if pieceNumberMethod is used in a for loop like:
for (int i = 0; i < pieceNumberMethod; i++) {
}
The for loop will never stop.
Thanks!
You are basically calling getPieceNumber twice so in the second call the number changes.
int pieceNumberMethod = boardAdap.getPieceNumber();
Log.v("xx", "" + pieceNumberMethod);
int pieceNumberInt = boardAdap.pieceNumber;
if (pieceNumberInt == 32) {
Log.v("xx", "int comparison worked");
}
if (pieceNumberMethod == 32) {
Log.v("xx", "method comparison worked");
}
Try calling method once.Hope that works!
The problem is comparing the strings. You need equals("NONE")
String none = new String("NONE");
int count = 32;
System.out.println(count);
for (int i = 0; i < 64; i++) {
if (none != "NONE") {
count++;
}
}
System.out.println(count);
If you run this code it will print different values for "count" despite value of "none"

Recursive function that converts integer to binary string?

So I know how I would go about writing a function that would simply print out the converter integer into binary like this:
private void convertBinary(int num) {
if(num > 0){
convertToBinary(num/2);
System.out.print(num%2 + "");
}
}
However, I'm not sure how I would do this if I wanted to return it as a string, especially with recursion since if I initialize the string as the beginning of the method it will reset the string during each recursive call.
Rather than give you code you can copy/paste, I'll solve a similar problem and you can apply the same technique.
Here's the print version of recursively printing 'A' n times:
void printTimes(int n) {
if(n > 0) {
printTimes(n-1);
System.out.print("A");
}
}
Now here's a version that returns a String:
String stringTimes(int n) {
if(n > 0) {
return stringTimes(n-1) + "A";
} else {
return "";
}
}
This should help you write your toBinary method.
Although this is close to your original, I like to be consistent in my recursive methods, in handling the terminating clause first, so more like:
String stringTimes(int n) {
if(n == 0) {
return "";
}
return stringTimes(n - 1) + "A";
}
Note that recursion is only appropriate to this particular problem, in Java, for learning purposes.
Advice 1: function name ... ConvertToBinary vs ConvertBinary
Advice 2: your result will be reverted this way (lsb on left)
Advice 3: get the return value from conversion and concatenate it with n%2 as output
But you're close enough.
BTW is it for some educational purpose? Recursion is quite inefficient for converting something to binary :)
class Class {
public static void main(String... args) {
System.out.println(intToBinary(1));
System.out.println(intToBinary(8));
System.out.println(intToBinary(15));
System.out.println(intToBinary(1234567));
}
private static String intToBinary(final int i) {
if (i == 0) {
return "";
} else {
return intToBinary(i / 2) + Integer.toString(i % 2);
}
}
}

Searching for a specific number in a int variable

I'm currently "learning" JavaScript + Android Studio for school and I got a little problem for which I can't find the right answer on Google:
I want to know if an int variable has a specific number, for example, I'm looking for the number 7 now int numberOne = 25824 doesn't have a 7 inside, but int numberTwo = 12387 does have one. Is there a way to search for a specific number in int variables?
I tried converting the int into a new string variable, but somehow this doesn't work :(
Here's some code I'm working with:
public int round = 1;
public String nummerSieben = "" + round;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (round % 7 == 0 || nummerSieben.contains("7")==true) {
....
} else {
....
}
}
});
Thank you for your help!
public int round = 1;
public String nummerSieben = "" + round; // nummerSieben is now "1"
You're hard-coding the value of nummberSieben. You need presumably get some value from the view, and test that. If you get it as in int, use
Integer.toString(i).contains("7") // i is whatever number you get from your view.
If you get it as a String, then half the work is already done, and you just need
i.contains("7")
As noted above, this has nothing to do with JavaScript - both your example and my answer are in Java.
Couple of things:
Your comparison is not right, method String:contains() returns a boolean,
Module % does not assert you the number will contain 7 or one of it's multiples.
Integer.toString(value) converts easily your int to String.
Knowing this, you can do:
if (Integer.toString(round).contains("7")) {
// IT CONTAINS THE NUMBER!
} else {
// IT DOES NOT CONTAIN THE NUMBER
}
Here is perfect solution of your problem
public class Finder {
static int round = 123456789;
static String str = String.valueOf(round);
public static void main(String... args) {
if (str.contains("7")) {
System.out.println("Found");
} else {
System.out.println("Can't found...");
}
}
}
Just convert your integer to String and then try to found the specific value from that string.
You don't have to convert to string in order to search specific digit in integer.
You can use math for that purpose.
Here is the code:
private static boolean isFound(int round) {
while (round > 0) {
if (round % 10 == 7)
return true;
round /= 10;
}
return false;
}
basically what this code do is checking each last digit if it's equals to 7 if not he divides the num by 10 and remove the last digit and after checking again, it will do so until no digit left (num=0) or he will find 7.

if condition to check if only one variable is set of the four variables at any point in JAVA

I want to display an error if more than one of the four variables is set...
In Java..this is what I came up with..
if( (isAset() && isBset()) || (isBset() && isCset()) || (isCset() && isDset()) || (isDset() && isAset()) )
attri.greedySelectionException(..);
I wanted to check if there is a better way of doing this..?
How about you use a counter and then compare it to 1?
Something like...
int i = 0;
if (isAset()) i++;
if (isBset()) i++;
if (isCset()) i++;
if (isDset()) i++;
if (i > 1)
...
Alternatively, if you are checking properties of a certain object, you could use some reflection to iterate through the relevant properties instead of having one if statement per property.
Edit: Take a look at Marius Žilėnas's varargs static method below for some tidier code, i.e. using (changed the oldschool for to a for-each and the ternary expression for an if):
static int trueCount(boolean... booleans) {
int sum = 0;
for (boolean b : booleans) {
if (b) {
sum++;
}
}
return sum;
}
instead of several if statements.
You can simplify this expression with :
if((isAset() || isCset()) && (isBset() || isDset()))
attri.greedySelectionException(..);
Wolfram alpha made the work for you :
Original expression
You can verify with the truth tables :
Original
Final
In Java 8 you can solve this problem with Streams in an elegant way (assuming your values are null if they are not set):
if (Stream.of(valueA, valueB, valueC, valueD).filter(Objects::nonNull).count() != 1) {
/* throw error */
}
If you have control on the implementation of isAset(), isBSet, isCSet, & isDset methods, you can achieve this with much more clarity if you return 1 or 0 instead of true or fales from this functions. These functions are to be created as below...
public int isAset()
{
return (A != null) ? 1 : 0;
}
To verify if more than one variable is set use use something like below...
if( isASet() + isBSet() + isCSet() + isDSet() > 1)
ThrowMoreAreSetException()
If you don't have control on this here is another way of doing it...
int count = isASet() ? 1 : 0;
count+= isBSet() ? 1 : 0;
count+= isCSet() ? 1 : 0;
count+= isDSet() ? 1 : 0;
if(count > 1)
ThrowMoreAreSetException()
By following either of these approches, code will be less clumsy and more readable than doing somany comparision combinations.
I suggest using varargs ... (see Java tutorial) and make a function that calculates how many trues was given. The following code to demonstrates it:
public class Values
{
public static boolean isASet()
{
return false;
}
public static boolean isBSet()
{
return true;
}
public static boolean isCSet()
{
return true;
}
public static boolean isDSet()
{
return true;
}
public static int booleans(boolean... booleans)
{
int sum = 0;
for (int i = 0; i < booleans.length; i++)
{
sum += booleans[i] ? 1 : 0;
}
return sum;
}
public static void main(String[] args)
{
System.out.println(
booleans(isASet(), isBSet(), isCSet(), isDSet()));
if (1 < booleans(isASet(), isBSet(), isCSet(), isDSet()))
{
System.out.println("Condition met.");
}
}
}
Try this:
if (!(isAset ^ isBset ^ isCset ^ isDset))
This will true only is any one is true or else false.

Cannot find symbol error

thank you in advance for helping out with this relatively simple (I hope) problem that I seem to be encountering. whenever I try to compile my programming assignment, I am met with a "cannot find symbol error." I point out where the error occurs in the code itself. Thanks again!
public class SSN
{
private int one;
private int two;
private int three;
public SSN(int first, int second, int third) throws Exception
{
if(first > 99 || first < 1 || second > 999 || second < 1 || third > 9999 || third < 1)
{
}
else
{
one = first;
two = second;
three = third;
}
}
//method that turns ###-##-#### string into 3 int SSN object
public static SSN valueOf(String ssn)
{
String firstpart;
firstpart = ssn.substring(0, 2);
String secondpart;
secondpart = ssn.substring(4, 5);
String thirdpart;
thirdpart = ssn.substring(7, 10);
int One = Integer.parseInt(firstpart);
int Two = Integer.parseInt(secondpart);
int Three = Integer.parseInt(thirdpart);
System.out.println(firstpart);
//This is where the cannot find symbol error occurs (return SSN(One, Two, Three), //and I am clueless as to why.
//Any insight as to why this error is occurring would be much appreciated!
return SSN(One, Two, Three);
}
public String toString()
{
return one + "-" + two + "-" + three;
}
}
return new SSN(One, Two, Three);
^^^
You're trying to create a new SSN(...) by calling the constructor.
The compiler si looking for a method named "SSN" but there is not such method ( the compiler can't find that symbol ) You were trying to create a new object not invoking a method thus you need to inlcude the new keyword as Erik and SLaks said.
return new SSN( One, Two, Three );

Categories

Resources