Private Methods: Describing Errors [closed] - java

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.

Related

Client Class Error in Java

Now, I also just have a simple question on the client class below, an error I'm getting, how to fix that error, and properly print (this.toString())
import java.io.*;
import java.util.Scanner;
public class IndexClient
{
File file = new File("file.txt");
System.out.println(this.toString());
}
Basically, I am getting an error on the second to last line that says identifier expected right before the after the println and before the first parentheses. Why am I getting that error, how would I fix that error, and then how would I successfully print (this.toString())?
Update Number 1:
I am not sure that this is entirely necessary; however, if you need it, my toString() method is below:
public String toString()
{
String sb = "";
for (int d = 0; d < words.size(); d++)
{
sb += "The word: " + words.get(d) + System.lineSeparator();
}
return sb;
}
Update Number 2:
I really appreciate all the help and constructive criticism of the code that I can get. I hope I didn't turn this simple question into one too complex. Thank you very much :)
Update Number 3:
I am sorry for leaving so many notes. However, I was only just wondering if this is a common question that any of you guys see a lot because it seems like this comes up a lot in class, and the teacher assisstant can't answer the question. Thanks again :)
You can't use :
System.out.println(toString());
Out side a method, you can use it inside a method or you can create your main method :
public void myMethod(){
System.out.println(toString());
}
Or
public static void main(String args[]){
System.out.println(toString());
}
You cannot have code outside a method in a java class.
You must create an object of your class to access this.
A correct minimal implementation would look like that (taken from the Online Java IDE):
import java.lang.Math; // headers MUST be above the first class
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
OtherClass myObject = new OtherClass("Hello World!");
System.out.print(myObject);
}
}
// you can add other public classes to this editor in any order
public class OtherClass
{
private String message;
private boolean answer = false;
public OtherClass(String input)
{
message = "Why, " + input + " Isn't this something?";
}
public String toString()
{
return message;
}
}

need some beginner guide about classes [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I just started learning Java and I have a problem with defining a class.
I defined some variables in a class, but everywhere I wrote a command for printing a value of a string (or other variables) I got an error that says "cannot find symbol". Does that mean I can't use a print command in a class? Can you do a favor and simply explain me what to do?
Here is my codes (it's just for testing):
class Variable {
int m = 15;
boolean myb = true;
double mon = 2.4;
}
if you have
class Variable {
public int m = 15;
public boolean myb = true;
public double mon = 2.4;
}
iv'e added public modifier so fields are accessible
then your print code should be
public static void main(String[] args) {
Variable object=new Vairable(); //create instance of class
System.out.println(object.m);
System.out.println(object.myb);
System.out.println(object.mon);
}
You would need to print from a method within the class, not just in the class.
class Variable {
int m = 15;
boolean myb = true;
double mon = 2.4;
public void printVars() {
System.out.println("m: " + m);
System.out.println("myb: " + myb);
System.out.println("mon: " + mon);
}
}
After that, you would create a new Variable and call it's printVars() method.
Or, if this class is what you're trying to run, you could put your main in here.
class Variable {
static int m = 15;
static boolean myb = true;
static double mon = 2.4;
public static void main(String[] args) {
System.out.println("m: " + m);
System.out.println("myb: " + myb);
System.out.println("mon: " + mon);
}
}

Java - Subclasses of Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Disclaimer: I'm a beginner so feel free to point stuff out...
I have a superclass composed by an array of int with 8 values, now i want to create a subclass to randomly pick 4 items in the array and store them in another Object.
Superclass:
public class SideDeck{
public static final int MaxValue = 6;
public static final int MinValue = -6;
public static final int MaxArrayValue = 8;
public final int[] sidecards = new int[MaxArrayValue];
public SideDeck(){
for(int i=0;i<MaxArrayValue;i++){
sidecards[i]=0;
}
}
public SideDeck(int sidecards1,int sidecards2,int sidecards3,int sidecards4,int sidecards5,int sidecards6, int sidecards7, int sidecards8){
sidecards[0]=sidecards1;
sidecards[1]=sidecards2;
sidecards[2]=sidecards3;
sidecards[3]=sidecards4;
sidecards[4]=sidecards5;
sidecards[5]=sidecards6;
sidecards[6]=sidecards7;
sidecards[7]=sidecards8;
}
public boolean ValidSidedeck(){
int check=0;
if (sidecards[0]!=0) {
for(int i=0;i<MaxArrayValue;i++){
if ((sidecards[i] > MinValue) && (sidecards[i] < MaxValue)){
check=1;
} else{
check=0;
break;
}
}
} else {
check=0;
}
if (check==1){
return true;
} else {
return false;
}
}
public String toString(){
String s="";
for(int i=0;i<MaxArrayValue;i++){
s+=(" || Card n° " + (i+1) + " = " + sidecards[i]);
}
return s;
}
public void ResetSidedeck(){
if (sidecards[0]!=0) {//why check it? what if we just run it?
for(int i=0;i<MaxArrayValue;i++){
sidecards[i]=0;
}
}
}
}
Subclass: (Not really sure what to do here… ) Basically it should pick 4 random positions from the .super and store them here, just that i have no clue how to create the object this way. And passing the super as constructor doesn't seem right since it's gonna pass the Object and not the array(and i don't need the full array anyway). Main thing is that i wanna keep the superclss like that, maybe just adding a method there so extract the 4 values..and passing them as arguments…?
import java.lang.Math;
public final class PlayableSideDeck extends SideDeck{
private final static int MaxCArrayValue=4;
public final int[] sidecardsPlay = new int[MaxCArrayValue];
public PlayableSideDeck(SideDeck sidecards){
/* sidecardsPlay[0]=0;
sidecardsPlay[1]=0;
sidecardsPlay[2]=0;
sidecardsPlay[3]=0;*/
// SetDeck();//<-Can i call a private method in the constructor
}
public void SetDeck(){
/* for(int j=0;j<4;j++){
int position=(super.sidecards[PickDeck()]);//<--this is the main problem.. since it's gonna call the object i guess.
sidecards[j]=position;
System.out.println(/*"i= " + i + *//* " ||| j= " + j + "|||| new sidecard= " + sidecards[j] + " |||| old sidecard=" + super.sidecards[PickDeck()]);
}*/
for(int j=0;j<MaxCArrayValue;j++){
sidecardsPlay[j]=(super.sidecards[PickDeck()]);
System.out.println(/*"i= " + i + */ " ||| j= " + j + "|||| new sidecard= " + sidecardsPlay[j] + " |||| old sidecard=" + super.sidecards[PickDeck()] + "|| random= " + PickDeck());
}
}
public int PickDeck(){
return ((int)(Math.random() * 8));
}
public String toString(){
String s="";
for(int i=0;i<MaxCArrayValue;i++){
s+=(" || Card n° " + (i+1) + " = " + sidecards[i]);
}
return s;
}
}
Thanks.
I'm not sure how you plan to use PlayableSideDeck, so I'll answer answer this two ways and you can pick the most fitting answer.
First, as the book Effective Java (by Josh Bloch) points out, you should favor composition over inheritance. By using composition you have your answer to the question of whether you should pass an instance of SideDeck to the constructor of PlayableSideDeck - you will have to since you won't be inheriting any access to SideDeck. Anyway, I'd recommend reading Item 16 in the book (google for it, there are copies available online) and see if composition doesn't better fit your needs.
Second, if you decide to go with inheritance, you don't need to pass an instance of SideDeck to the constructor of PlayableSideDeck. This is because when you create an instance of PlayableSideDeck you are automatically creating an instance of SideDeck along with it. All constructors in Java will implicitly call super() (which is the superclasses's default constructor) if you don't explicitly provide another such call yourself. For example, you could prevent the implicit call to super() like so:
public class BaseClass {
protected String strValue;
public BaseClass () {
strValue = "";
}
public BaseClass (String str) {
strValue = str;
}
}
public class SubClass extends BaseClass {
private int intValue;
SubClass (String str, int i) {
super (str);
intValue = i;
// note that since strValue is protected, SubClass can access directly
System.out.println ("strValue = " + strValue);
}
}
In this example, if you call new SubClass ("foobar") then you will see strValue = foobar printed on the console.
If BaseClass didn't have a zero argument constructor you would, in fact, be required to call super(str) since the compiler wouldn't be able to figure out how to do it for you.
Also, since you asked, here are a few other tips and pointers:
In the constructor SideDeck() you explicitly initialize all values of the array to 0, which isn't necessary. They will already all be 0. If you needed to init them to 0 then you'd be better off avoiding code duplication by calling ResetSideDeck. Speaking of which, you can shorten that code to Arrays.fill (sidecards, 0); (be sure to import java.util.Arrays).
Yes, you can call private methods from a constructor - but only private methods that are part of the local class, not any of the superclasses (you can, however, call protected methods of superclasses).
You're right about not checking sidecards[0] == 0 since there's little efficiency to be gained unless MaxArrayValue becomes very large.
Your class member variables such as sidecards should be private (or maybe protected if you need to access them from a subclass). Use getter/setter methods to access them.
Lastly, Java naming conventions would tell you to use a lower-case letter for method names (e.g. setDeck, pickDeck, resetDeck, etc.), and for even more idiomatic Java you could rename ValidaDeck to isValidDeck (since it returns a boolean). For the constants such as MaxArrayValue the convention is to use all upper-case with underscores between words, e.g. MAX_ARRAY_VALUE.
Hope this all helps!

Why doesnt string.equals("astring") work? [closed]

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.

Null Pointer Exception [closed]

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
I am working on some project in java.
Here I'm stuck at this problem and not able to figure out where I am going wrong.
I have made two classes: Test and Child.
When I run the code I am get a NullPointerException.
package com.test;
public class Test {
child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method() {
String[] b;
b = newchild.main();
int i = 0;
while (i < b.length) {
System.out.println(b[i]);
}
}
}
package com.test;
public class child {
public String[] main() {
String[] a = null;
a[0] = "This";
a[1] = "is";
a[2] = "not";
a[3] = "working";
return a;
}
}
Here's the problem:
String[] a = null;
a[0]="This";
You're immediately trying to dereference a, which is null, in order to set an element in it. You need to initialize the array:
String[] a = new String[4];
a[0]="This";
If you don't know how many elements your collection should have before you start populating it (and often even if you do) I would suggest using a List of some sort. For example:
List<String> a = new ArrayList<String>();
a.add("This");
a.add("is");
a.add("not");
a.add("working");
return a;
Note that you have another problem here:
int i=0;
while(i<b.length)
System.out.println(b[i]);
You're never changing i, so it will always be 0 - if you get into the while loop at all, you will never get out of it. You want something like this:
for (int i = 0; i < b.length; i++)
{
System.out.println(b[i]);
}
Or better:
for (String value : b)
{
System.out.println(value);
}
This is the problem:
String[] a = null;
a[0]="This";
They highlighted the problem of your probably the definition of null pointer exception would give you an idea what and where to find the problem in future. From java api doc, it defined what is npe and under what situation it will be thrown. Hope it help you.
Thrown when an application attempts to use null in a case where an object is required. These include:
* Calling the instance method of a null object.
* Accessing or modifying the field of a null object.
* Taking the length of null as if it were an array.
* Accessing or modifying the slots of null as if it were an array.
* Throwing null as if it were a Throwable value.
package test;
public class Test {
child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method()
{
String[] b;
b = newchild.main();
int i=0;
while(i<b.length){
System.out.println(b[i]);
i++;
}
}
}
package test;
public class child {
public String[] main() {
String[] a = {"This","is","not","Working"};
return a;
}

Categories

Resources