Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
Why don't I get 20 after delivering e.g. "Obsidian" to Test(String pStr) if I call getMatInt() ?
Also tried .toString() after all String-declariations, also declarated e.g. "Obsidian" as new String a. Nothing works.
getBonus is aways returning a 0 instead of a 20/30/... .
I already tried "Obsidian" and "obsidian", both doesnt work for me ...
public class test
{
private String str;
private int matInt;
private int bonus;
private int magic;
public test(int pMagic, String pStr)
{
int magic = pMagic;
str = pStr;
}
private void materialEquals()
{
if(str.equals("Obsidian"))
{
matInt = 20;
}
.....
}
private void calcBonus()
{
materialEquals();
bonus = magic * matInt;
}
public int getBonus()
{
calcBonus();
return bonus;
}
}
try:
public int getMatInt()
{
materialEquals();
return matInt;
}
There is no reason for this in your constructor: str = new String(pStr);, just use str = pStr.
In fact, you might be better off setting matInt in your constructor:
public test(String pStr)
{
str = pStr;
materialEquals();
}
And depending on how many materials you have, you might want to look into using enumeration.
Ok after your edits:
public int getBonus()
{
calcBonus(); //bonus won't be calculated otherwise
return bonus;
}
After further edits:
Your constructor is wrong, you're not initializing int magic. Try this constructor instead.
public test(int pMagic, String pStr)
{
this.magic = pMagic; //int magic = pMagic was a new variable only in the constructor scope
this.str = pStr;
calcBonus();
}
Also you might as well calculate the bonus on construction.
You will need to call materialEquals() so that 20 can be assigned to matInt upon equals comparison, as integers are always initialized to default value 0 upon declaration.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So far i tried to add values from a stream to a list with peek() but later I found out that peek() is only used "to support debugging, where you want to see the elements as they flow past a certain point in a pipeline".
Now my question is whats the coding-convention here ?
Do I map it in a second stream or can I map it one String like my Code with Peek() ?
final int range = 9;
List <String> help = new ArrayList<String>();
//random numbers to fill help
for(int i = 5;i< range;i++)
{
help.add(String.valueOf(i+(i*2)+(i*(i+2))) );
}
List<Test> others = new LinkedList<>();
List<Test> tests = help.stream().map(s-> new Test(s,(int) Integer.valueOf("10")))
.peek(t->System.out.println(t.getText()))
.peek(t-> others.add(t)).collect(Collectors.toList());
The class Test looks like this:
public class Test
{
String text;
int id;
public Test(String text, int id) {
this.text = text;
this.id = id;
}
public String getText() {
return text;
}
public int getId() {
return id;
}
}
You could add that functionality to the lambda in the mapping part:
List<Test> tests = help.stream().map(
s-> {
Test t = new Test(s,(int) Integer.valueOf("10")));
System.out.println(t.getText());
others.add(t)
return t;
}
.collect(Collectors.toList());
That simply moves your extra steps into an existing step, avoiding any further loops etc
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm making a quiz program. First step, I'm taking the quiz questions and their correct answers from the teacher/ user. I have a child class named TrueFalseQuestion which takes the boolean model answer and the string question as a parameter. I've made an array of TrueFalseQuestion type and I'm stuck at this part where I run the code, insert a question and no matter whether the model answer I've inserted is true or false, it's always stored as false when I print it out. HELP?
Here's this part of my code:
System.out.println("How many true or false questions would you like to include in your quiz?");
int l=s.nextInt();
TrueFalseQuestion[] qu2= new TrueFalseQuestion[l];
int x;
for(x=0;x<l;x++){
System.out.println("Please insert question "+(x+1)+":\n");
String Q2=s.next();
System.out.println("Please insert the correct answer");
boolean A2=s.nextBoolean();
qu2[x]=new TrueFalseQuestion(Q2,A2);
System.out.println(qu2[x].GetCorrectAnswer());
}
EDIT: Here's the TrueFalseQuestion code
public class TrueFalseQuestion extends Question {
private boolean CorrectB;
public TrueFalseQuestion(String qu, boolean b){
super(qu);
}
#Override
public void GetQuestion() {
System.out.println(getMyText()+"\n Is this statement true or false?");
}
#Override public String GetAnswer() {
System.out.println("Insert Answer: ");
boolean MyAnswer=s.nextBoolean();
return Boolean.toString(MyAnswer);
}
#Override public String CheckAnswer() {
return Boolean.toString(GetAnswer().equalsIgnoreCase(Boolean.toString(GetCorrectAnswer())));
}
/** * return the MyAnswer / /* * return the CorrectAnswer / public boolean GetCorrectAnswer() { return CorrectB; } /* * return the MyAnswer */
}
your problem is your constructor:
public TrueFalseQuestion(String qu, boolean b){
super(qu);
}
You don't set the field CorrectB so it defaults to its default value which in java is false
the fix is
public TrueFalseQuestion(String qu, boolean b){
super(qu);
CorrectB = b;
}
Problem is nextInt() leaves "\n" in the stream and when next() executes in
String Q2=s.next();
It reads "\n" and doesn't gives you an opportunity to input Question.
Try this:
System.out.println("How many true or false questions would you like to include in your quiz?");
int l=Integer.parseInt(nextLine());
TrueFalseQuestion[] qu2= new TrueFalseQuestion[l];
int x;
for(x=0;x<l;x++){
System.out.println("Please insert question "+(x+1)+":\n");
String Q2=s.nextLine();
System.out.println("Please insert the correct answer");
boolean A2=s.nextBoolean();
qu2[x]=new TrueFalseQuestion(Q2,A2);
System.out.println(qu2[x].GetCorrectAnswer());
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I write the code
public class keys {
private static final String[] keyss = {
"HGDLV-KLLQC-DM3ON-MAUOX-FNQK5",
"HQKLD-NYRDL-NJXCV-BVCKF-NRKLC",
"LDFCV-BDJCQ-VMFQV-FNRKC-NFCFL"
//and many more
};
public static String getKey(String key) {
boolean b = Arrays.asList(keyss).contains(key);
if (b == true) {
key = "approved";
} else {
key = "unapproved";
}
return key;
}
and gets the approved for all Strings even if the above dosen't match with the user specified string
Compare Strings using equals. Also the implementation of getKeys() is too complicated and redundant.. Consider changing it to:
public class Keys {
private static final String[] keys = {
"HGDLV-KLLQC-DM3ON-MAUOX-FNQK5",
"HQKLD-NYRDL-NJXCV-BVCKF-NRKLC",
"LDFCV-BDJCQ-VMFQV-FNRKC-NFCFL"
//and many more
};
public static String getKey(String key) {
for(String current : keys){
if(current.equals(key)){
return "approved";
}
}
return "unapproved";
}
}
No need to use Arrays in the way you use it, nor a boolean switch..
You might want to check out this question to read about comparing Strings.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
This is my example code to test HashSet.
I expect that the result is [3K,1K] but the this code results in [1K,3K,3K]
Could you let me know why the code not call equals?
import java.util.HashSet;
class SutdaCard{
private int num;
private boolean isKwang;
SutdaCard(){
this(1,true);
}
SutdaCard(int num, boolean isKwang){
this.num = num;
this.isKwang = isKwang;
}
public String toString(){
return num+(isKwang ? "K":"");
}
public boolean equals(Object obj){
String compareValue = obj.toString();
String thisValue = toString();
System.out.println("equals");
return thisValue.equals(compareValue);
}
public int hashcode(){
return toString().hashCode();
}
}
class exercise11_11 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<SutdaCard> set = new HashSet<SutdaCard>();
set.add(new SutdaCard(3,true));
set.add(new SutdaCard(3,true));
set.add(new SutdaCard(1,true));
System.out.println(set);
}
}
You haven't overridden hashCode() properly. Try:
#Override
public int hashCode() {
return this.toString().hashCode();
}
Since the Set uses the hashCode() from Object in your code, the two SutdaCards hash codes won't match, and equals() is never called.
If you add the #Override annotation, the compiler will check that you are actually overriding something, and generate a warning if you have a spelling error.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on the following assignment: An attempt to moveOn or backUp or to evaluate seesCD when it is illegal causes an abrupt System.exit(0) without explanation. The user would appreciate a tracing output in such cases. Revise these three methods to call a private method that explains the problem (with showMessageDialog) and then terminates.
I wrote the following code (please scroll down the code):
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Vic extends Object
{
private static final String NONE = "0";
/////////////////////////////////
private String itsSequence = "";
private int itsPos = 1;
private final int itsID; // assigned by the constructor
private void trace (String action)
{
System.out.println ("Vic# " + itsID + ": " + action
+ itsPos + "; sequence= " + itsSequence);
} //======================
public void backUp()
{
if (itsPos == 1)
error("Could not backUp");
itsPos--;
trace ("backUp to slot ");
} //======================
public void moveOn()
{
if ( ! seesSlot())
error("Could not moveOn");
itsPos++;
trace ("moveOn to slot ");
} //======================
public boolean seesSlot()
{
return itsPos < itsSequence.length();
} //======================
public boolean seesCD()
{
if ( ! seesSlot())
error("Can't see CD, there is no slot");
String s = itsSequence.substring (itsPos, itsPos + 1);
return ! s.equals (NONE);
} //======================
private void error(String message)
{
JOptionPane.showMessageDialog(null, "ERROR: " + message);
System.exit(0);
}
}
When I compile I receive the following error message:
"variable itsID might not have been initialized".
and this line is highlighted."public class Vic extends Object"
The problem is that you have a final instance variable (which means that it has to be assigned a value exactly once during construction), but you don't have a constructor actually assigning it anywhere.
There's a comment that says assigned by the constructor on that field, but there's no explicit constructor. Perhaps you're supposed to write one, or it got removed at some point in the process of turning this code into an assignment.
itsId isn't set anywhere, that explains your error.
But in general, this type of problem is solved with try and catch blocks and thrown errors. I'm sure you are about to learn about those.