I need help computing this code i have to return a string representation in the
ID: 3575646 • Letter: I
Question
I need help computing this code i have to return a string representation in the toString method if the boolean value is true or false.
this is part of my code..am supposed to return"and is valid.", if the boolean value is true or "is not valid.", if its false.
public String toString()
{
for(int x = 0; x < number.length(); x++)
{
char c = number.charAt(x);
if(Character.isDigit(c)){
builder.append(c);
}
}
return builder.toString() + " was issued by " + getIssuer();
}
public boolean isValid()
{
if(word.length() % 2 == 0){
for(int i = 0; i < word.length(); i++)
{
char c = word.charAt(i);
int num = Character.getNumericValue(c);
if(i % 2 == 0)
{
n = num * 2;
if(n > 9)
{
n -=9;
}
sum +=n;
}
else
sum+= num;
}
}
else
{
for(int x = 0; x < word.length(); x++)
{
char c = word.charAt(x);
int num = Character.getNumericValue(c);
if(x % 2 != 0)
{
n = num * 2;
if(n > 9)
{
n -=9;
}
sum +=n;
}
else
sum += num;
}
}
if(sum % 10 == 0)
value = true;
else
value = false;
return value;
}
Explanation / Answer
class ConditionalToString
{
public String toString()
{
for(int x = 0; x < number.length(); x++)
{
char c = number.charAt(x);
if(Character.isDigit(c)){
builder.append(c);
}
}
String out = builder.toString() + " was issued by " + getIssuer(); //Will append the actual instruction.
if(this.isValid()) //The isValid() method is called, and if it returns true.
out += " and is valid."; //"and is valid" is appended to the output.
else //If not.
out += " is not valid."; //"is not valid" is appeneded to the output.
return out; //And returns the output.
}
public boolean isValid()
{
if(word.length() % 2 == 0){
for(int i = 0; i < word.length(); i++)
{
char c = word.charAt(i);
int num = Character.getNumericValue(c);
if(i % 2 == 0)
{
n = num * 2;
if(n > 9)
{
n -=9;
}
sum +=n;
}
else
sum+= num;
}
}
else
{
for(int x = 0; x < word.length(); x++)
{
char c = word.charAt(x);
int num = Character.getNumericValue(c);
if(x % 2 != 0)
{
n = num * 2;
if(n > 9)
{
n -=9;
}
sum +=n;
}
else
sum += num;
}
}
if(sum % 10 == 0)
value = true;
else
value = false;
return value;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.