I have a problem with that i can't get my string to be named with a string! here is my code.
public class Load {
int num = 0;
public String getstuff(){
num++;
String snum = new String("" + num);
return snum;
}
String name = this.getstuff();
public void AddString(String f, int v){
String name = this.name;
String name = new String(f + v);
}
public Load(String s){
}
}
Avoid using String constructor.
public class Load {
int num = 0;
public String getstuff() {
num++;
return "" + num;
}
String name = this.getstuff();
public void AddString(String f, int v){
this.name = this.name + f + v;
// Or
// this.name = f + v;
// Whichever behavior you want.
}
public Load(String s){
}
}
Hope this helps.
Good luck.
Related
I am this close to finally completing this assignment, but I've hit a roadblock. For some reason I can't get call aspects of the class in my methods. Does anyone have a way of doing this that works? I've put comments next to the three parts I'm referring to. I do not know what is causing these errors, and Im grateful for any help.
public class Main
{
public static int w = -1;
public static int x = 0;
public static int y = 0;
public static int z = 0;
public static String[] names;
public static int[] years;
public static String[] studios;
public static class Movie{
// instance variables
private int year;
private String title;
private String studio;
private int placement;
// Constructor for objects of class Movie
Movie(String title, int year, String studio)
{
// initialize instance variables
this.title = title;
this.year = year;
this.studio = studio;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public void setPlacement() {
w+=1;
this.placement = w;
}
public int getPlacement() {
return placement;
}
public String getStudio()
{
return studio;
}
public void setStudio(String studio)
{
this.studio = studio;
}
public int getYear()
{
return year;
}
public void setYear(int year)
{
this.year = year;
}
public String toString()
{
String str = String.format("%-30s %4d %-20s", title, year, studio);
return str;
}
}
public static void arrNames(String name) {
x+=1;
names = new String[x];
names[(x-1)] = name.getTitle(); //error here, why can't I just use getTitle()?
}
public static void arrYear(String name) {
y+=1;
years = new int[y];
years[(y-1)] = name.getYear(); //same error
}
public static void arrStudio(String name) {
z+=1;
studios = new String[z];
studios[z-1] = name.getStudio(); //same error
}
public static void setGroup(String name) {
arrNames(name);
arrYear(name);
arrStudio(name);
}
public static void getGroups(String name) {
int a = x;
int b = y;
int c = z;
int d = 0;
int e = 0;
int f = 0;
System.out.println("Names Category: ");
while (a > 0) {
System.out.print(names[d] + " ");
d+=1;
a-=1;
}
System.out.println("Years Category: ");
while (b > 0) {
System.out.print(years[e] + " ");
e+=1;
b-=1;
}
System.out.println("Studios Category: ");
while (c > 0) {
System.out.print(studios[f] + " ");
f+=1;
c-=1;
}
public static void main(String[] args) {
Movie nemo = new Movie("Finding Nemo",2003,"Pixar");
setGroup(nemo.getTitle());
}
}
I will take this exemple:
public static void arrYear(String name) {
y+=1;
years = new int[y];
years[(y-1)] = name.getYear(); //same error
}
You are trying to use the method getYear on the variable name and the name is a String and not a Movie Object
You could just replace the argument from String to Movie like that:
public static void arrYear(Movie name) {
y+=1;
years = new int[y];
years[(y-1)] = name.getYear(); //same error
}
and it should work for all your functions
I've created a Java class called 'Book'. Using this class I'm willing to update information about a new object 'book1'. I'm also wanting to add Author information into the object 'book1'. So, I've dynamically allocated memory using a class-array called 'Author[ ]'. By this I mean there's a separate code in which I've created a class called 'Author' with its own set of instance variables. I'm not getting into that now. However, when I'm testing the class 'Book' using another class called 'TestBook' there's no compilation error BUT I'm getting the following message in the console window when I'm running the code:
Exception in thread "main" java.lang.NullPointerException
at Book.addAuthors(Book.java:34)
at TestBook.main(TestBook.java:12)
The code for 'Book' is shown below:
public class Book {
private String name;
private Author[] A = new Author[];
private int numAuthors = 0;
private double price;
private int qtyInStock;
public Book(String n, Author[] authors, double p) {
name = n;
A = authors;
price = p;
}
public Book(String n, Author[] authors, double p, int qIS) {
name = n;
A = authors;
price = p;
qtyInStock = qIS;
}
public Book(String n, double p, int qIS) {
name = n;
price = p;
qtyInStock = qIS;
}
public String getName() {
return name;
}
/*
public Author getAuthors() {
return A;
}
*/
public void addAuthors(Author newAuthor) {
A[numAuthors] = newAuthor; // THIS LINE IS WHERE THE ERROR POINTS TO
++numAuthors;
}
public void printAuthors() {
/*
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
*/
for (int i = 0; i < numAuthors; i++) {
System.out.println(A[i]);
}
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
public void setqtyInStock(int qIS) {
qtyInStock = qIS;
}
public int getqtyInStock() {
return qtyInStock;
}
/*
public String getAuthorName() {
return A.getName();
}
public String getAuthorEmail() {
return A.getEmail();
}
public char getAuthorGender() {
return A.getGender();
}
*/
public String toString() {
/*
return getName() + " " + getAuthor() + " Book price: " + getPrice() +
" Qty left in stock: " + getqtyInStock();
*/
//return getName() + " is written by " + A.length + " authors.";
return getName() + " is written by " + numAuthors + " authors.";
}
}
The code for 'TestBook' is shown below:
public class TestBook {
public static void main(String args[]) {
//Author[] authors = new Author[2];
//authors[0] = new Author("Tapasvi Dumdam Thapashki", "tapasvi#thapashki.com", 'M');
//authors[1] = new Author("Paul Rand", "paulie#aol.com", 'M');
Book book1 = new Book("The Quickie Man", 69.00, 5);
//System.out.println(book1.toString());
//book1.setqtyInStock(5);
//System.out.println(book1.toString());
//System.out.println(book1.getAuthorName() + " " + book1.getAuthorEmail());
//book1.printAuthors();
book1.addAuthors(new Author("Linda Lee", "lindalee#grinchtown.com", 'F'));
book1.addAuthors(new Author("Joseph Caputo", "caputo#lfp.com", 'M'));
System.out.println(book1.toString());
book1.printAuthors();
}
}
The code for 'Author' is shown below:
public class Author {
private String name;
private String email;
private char gender;
public Author(String n, String e, char g) {
name = n;
email = e;
gender = g;
}
public String getName() {
return name;
}
public void setEmail(String e) {
email = e;
}
public String getEmail() {
return email;
}
public char getGender() {
return gender;
}
public String toString() {
return getName() + " [" + getGender() + "] " + getEmail();
}
}
I'd like some help with this.
Initialize Author array with proper size like private Author[] A = new Author[4];
You forgot to specify the size of the Array.
private Author[] A = new Author[15];
For making a dynamic array you can use ArrayList.
private ArrayList<Author> list = new ArrayList<Author>();
addAuthors()
public void addAuthors(Author newAuthor) {
list.add(newAuthor);
}
printAuthors()
public void printAuthors() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
I don't know how to get a specific item for a generic list instance. Suppose I have something like this;
public class Column {
private String name;
private float width;
public Column(String name, float width) {
this.name=name;
this.width=width;
}
public String getName() {
return name;
}
and another class;
public class WriteColumn {
private List<Column> col = new ArrayList<>();
public void addColumn() {
col.add(new Column("yo", 0.1f));
col.add(new Column("mo", 0.3f));
writeColumn(col);
public void writeColumn(List<Column> col) {
String str = "";
for (Column col1 : col) {
str += col1 + " - ";
}
System.out.println("Cols: " + str);
}
public static void main(String[] args) {
WriteColumn wc = new WriteColumn();
wc.addColumn();
}
}
The output I want to get is the text part of the column but I am not getting it. Is there a simple way of doing it ?
I cannot get why you cannot use getName() method?
It should work:
public void writeColumn(List<Column> col) {
String str = "";
for (Column col1 : col) {
str += col1.getName() + " - ";
}
System.out.println("Cols: " + str);
}
Below code is working , Output :
Cols: yo - mo -
I guess this is what you are expecting.
package com.vipin.test;
import java.util.*;
class Column {
private String name;
private float width;
public Column(String name, float width) {
this.name=name;
this.width=width;
}
public String getName() {
return name;
}
}
public class WriteColumn {
private List<Column> col = new ArrayList<>();
public void addColumn() {
col.add(new Column("yo", 0.1f));
col.add(new Column("mo", 0.3f));
writeColumn(col);
}
public void writeColumn(List<Column> col) {
String str = "";
for (Column col1 : col) {
str += col1.getName() + " - "; //used getName()
}
System.out.println("Cols: " + str);
}
public static void main(String[] args) {
WriteColumn wc = new WriteColumn();
wc.addColumn();
}
}
I am working on a simple text-based rpg battler program as an introduction to Java. I seem to have a decent understanding of the majority of code, but I have ran into a couple of issues.
The issues I am having are in the Project class.
In my switch statement I am trying to use the setSpells() and setArrows() methods and I am getting a "cannot find symbol" error message. I realize that this is probably due to something I have set up incorrectly in the sub-classes, but I am unsure what that is.
The second issue is in the print statement pulling the character name by use of c.getName(). The c part of that statement gives the same error message.
Is there something simple that I am misunderstanding in these situations? Any help resolving this would be appreciated. Thank you.
Here is my main project class file:
package project;
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
System.out.println("Welcome to Lands of the Sun\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Please choose your class (wizard or elf): \n");
String classChoice = sc.next();
sc.nextLine();
System.out.print("Please choose a name for your " + classChoice + ": ");
String charName = sc.next();
sc.nextLine();
int healthVal = (int) (Math.random() * 10) + 1;
switch (classChoice) {
case "wizard":
{
Character c = new Wizard();
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setSpells(10);
break;
}
case "elf":
{
Character c = new Elf();
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setArrows(10);
break;
}
}
System.out.print(c.getName());
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Here is my Character class:
package project;
public abstract class Character {
private String name;
private int gold;
private int health;
public static int count = 0;
public Character()
{
name = "";
gold = 0;
health = 0;
}
public Character(String name, int gold, int health) {
this.name = name;
this.gold = gold;
this.health = health;
}
public void setName(String name)
{
this.name = name;
}
public String getName(){
return name;
}
public void setGold(int gold)
{
this.gold = gold;
}
public int getGold()
{
return gold;
}
public void setHealth(int health)
{
this.health = health;
}
public int getHealth()
{
return health;
}
#Override
public String toString()
{
return "Name: " + name + "\n" +
"Gold: " + gold + "\n" +
"Health: " + health + "\n";
}
public static int getCount()
{
return count;
}
public abstract String getDisplayText();
}
Here is my Wizard sub-class:
package project;
public class Wizard extends Character {
private int spells;
public Wizard()
{
super();
spells= 0;
count++;
}
public void setSpells(int spells)
{
this.spells= spells;
}
public int getSpells(){
return spells;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Spells: " + spells+ "\n";
}
}
And finally my Elf sub-class:
package project;
public class Elf extends Character{
private int arrows;
public Elf()
{
super();
arrows = 0;
count++;
}
public void setArrows(int arrows)
{
this.arrows = arrows;
}
public int getArrows(){
return arrows;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Arrows: " + arrows + "\n";
}
}
When you create one of your Characters...
Character c = new Elf();
You are downcasting the instance to "act" like Character, this is very useful feature in Object Oriented Programming, but is causing you issues in this case, as Character does not have the methods you are looking for.
Instead, start by assigning the class to a concrete version of the instance...
Elf elf = new Elf();
Apply the properties you need and then assign it to a Character reference...
Character c = null;
//...
switch (classChoice) {
//...
case "elf":
{
Elf elf = new Elf();
//...
c = elf;
}
}
c = elf;
for example...
Have a look at the section on Polymorphism for more details
Your issue is with these lines
Character c = new Wizard();
....
Character c = new Elf();
The character class itself doesn't have the setFireballs or SetArrows methods. You need to define the object as a wizard or elf in order to get access to said methods... EG:
Elf c = new Elf();
Wizard c = new Wizard();
etc
Character c = new Wizard();
Character has neither a setFireBalls method nor a setArrows method.
I have made the some changes to your code..
here is the final code.
package h;
import java.util.Scanner;
public class he {
public static void main(String[] args) {
System.out.println("Welcome to Lands of the Sun\n");
Character c = new Wizard();
Character e = new Elf();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Please choose your class (wizard or elf): \n");
String classChoice = sc.next();
sc.nextLine();
System.out.print("Please choose a name for your " + classChoice + ": ");
String charName = sc.next();
sc.nextLine();
int healthVal = (int) (Math.random() * 10) + 1;
switch (classChoice) {
case "wizard":
{
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setFireballs(10);
break;
}
case "elf":
{
;
e.setName(charName);
e.setGold(25);
e.setHealth(healthVal);
e.setArrows(10);
break;
}
}
System.out.print(c.getName());
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Wizard class
public class Wizard extends Character {
private int fireballs;
public Wizard()
{
super();
fireballs = 0;
count++;
}
public void setFireballs(int fireballs)
{
this.fireballs = fireballs;
}
public int getFireballs(){
return fireballs;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Fireballs: " + fireballs + "\n";
}
#Override
public void setArrows(int i) {
}
}
Elf class
public class Elf extends Character {
private int arrows;
public Elf()
{
super();
arrows = 0;
count++;
}
public void setArrows(int arrows)
{
this.arrows = arrows;
}
public int getArrows(){
return arrows;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Arrows: " + arrows + "\n";
}
#Override
public void setFireballs(int i){
}
}
abstract class Character
public abstract class Character {
private String name;
private int gold;
private int health;
public static int count = 0;
public Character() {
name = "";
gold = 0;
health = 0;
}
public Character(String name, int gold, int health) {
this.name = name;
this.gold = gold;
this.health = health;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setGold(int gold) {
this.gold = gold;
}
public void setHealth(int health) {
this.health = health;
}
public int getHealth() {
return health;
}
#Override
public String toString() {
return "Name: " + name + "\n" + "Gold: " + gold + "\n" + "Health: "
+ health + "\n";
}
public static int getCount() {
return count;
}
public abstract String getDisplayText();
public abstract void setFireballs(int i);
public abstract void setArrows(int i);
}
hope this helps...
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
Changed my code since I should protect my code from students against plagiarism.
I got this error when I tried to compile my code:
Unresolved compilation problem:
Type mismatch: cannot convert from Object to Entry
at SchoolManager.listGrade(SchoolManager.java:49)
at SchoolManager.main(SchoolManager.java:30)
mainClass.java
public class mainClass {
static Scanner scanner = new Scanner(System.in);
static ArrayList<C> c = new ArrayList();
static ArrayList<Object> ob = new ArrayList();
public static void main(String [] args){
while(true){
System.out.println("----------------------------------------------------------------------------");
System.out.println("New:1 Add:2 ListC:3 ListOb:4 AddE:5 ListE:6");
System.out.println("----------------------------------------------------------------------------");
System.out.print(">> ");
String option = scanner.nextLine();
if(option.equals("0")){
System.out.println(c.size()+" "+ob.size()+" ");
System.out.println("Bye");
break;
}else if(option.equals("1")){
c.add(createC());
}else if(option.equals("2")){
ob.add(createOb());
}else if(option.equals("3")){
listC();
}else if(option.equals("4")){
listOb();
}else if(option.equals("5")){
addE();
}else if(option.equals("6")){
listE();
}else{
System.out.println(" ");
}
}
}
private static void listE() {
System.out.print("");
String ob1 = scanner.nextLine();
Object ob = findOb(ob1);
if(ob==null){
System.out.println(" ");
}else{
System.out.println(" ");
System.out.println(ob);
System.out.println(" ");
for(int i=0;i<ob.getE().size();i++){ // this part is a problem.
Entry e = ob.getE().get(i); // this part is a problem.
System.out.println(e.getC()+"\t"+ge.getT()+"\t"+ge.getE());
}
}
}
private static void addE() {
System.out.print(" ");
String ob1 = scanner.nextLine();
Object ob = findOb(ob1);
if(ob==null){
System.out.println("Could not be found...");
}else{
addE(ob);
}
}
private static Object findOb(String ob1) {
for(int i=0;i<ob.size();i++){
if(ob.get(i).getID().equals(ob1)){
return ob.get(i);
}
}
return null;
}
private static void addE(Object ob) {
System.out.print("? ");
String c_id = scanner.nextLine();
C c = findC(c_id);
if(c==null){
System.out.println("Could not be found...");
}else{
System.out.print("T? ");
String t = scanner.nextLine();
System.out.print("E? ");
String ee = scanner.nextLine();
ob.AddE(new Entry(c,t,ee));
}
}
private static C findC(String c_id) {
for(int i=0;i<c.size();i++){
if(c.get(i).getID().equals(c_id)) return c.get(i);
}
return null;
}
private static void listOb() {
for(int i=0;i<ob.size();i++){
System.out.println(ob.get(i));
}
System.out.println();
}
private static void listC() {
for(int i=0;i<c.size();i++){
System.out.println(c.get(i));
}
System.out.println();
}
private static Object createObject() {
System.out.print("S? ");
String id = scanner.nextLine();
System.out.print("N? ");
String n = scanner.nextLine();
System.out.print("S? ");
String s = scanner.nextLine();
return new Student(id,n,s);
}
private static C createC() {
System.out.print("C? ");
String id = scanner.nextLine();
System.out.print("Ct? ");
String Ct = scanner.nextLine();
return new Course(id,Ct);
}
}
Object.java:
public class Object {
public String ID;
public String n;
public String s;
public ArrayList<C> c;
public ArrayList<Ob> s;
public ArrayList<Entry> e;
public Object() {
}
public Object(String id, String n, String s) {
this.ID = id;
this.n = n;
this.s = s;
c= new ArrayList<C>();
ob= new ArrayList<Ob>();
e= new ArrayList<Entry>();
}
public String getId() {
return ID;
}
public String getN() {
return n;
}
public String getS() {
return s;
}
public String getID() {
return getId();
}
public void AddE(Entry e) {
e.add(Entry); //this part is a problem.
}
public ArrayList<Object> getE() {
return ob; //this part is a problem.
}
public String toString() {
String result = ID + " " + n + " " + s;
for(int i=0; i < c.size(); i++) {
result += c.get(i).toString();
result += "\n";
}
return result;
}
}
C.java:
import java.util.ArrayList;
public class C {
String co;
String t1;
public ArrayList<Ob> ob;
public C(String id, String t1) {
co = id;
this.t1 = t1;
ob = new ArrayList<Object>();
}
public String getCo() {
return co;
}
public String getT1() {
return t1;
}
public String getID() {
return getCo();
}
public String toString() {
String result = co + " " + t1;
for(int i=0; i < ob.size(); i++) {
result += ob.get(i).toString();
result += "\n";
}
return result;
}
}
Entry.java:
public class Entry {
public C c;
public String t;
public String g;
public ArrayList<Ob> g;
public Entry(C c, String term, String gr) {
c=c;
t=t;
gr=gr;
g = new ArrayList<Ob>();
}
public Course getC() {
return c;
}
public String getE() {
return g;
}
public String getT() {
return t;
}
public String toString() {
String result = c+ " " + t+ " " + g;
for(int i=0; i < gr.size(); i++) {
result += gr.get(i).toString();
result += "\n";
}
return result;
}
}
How can I solve this error?
This is the error it is talking about:
GradeEntry ge = student.getGrades().get(i);
Says can't convert from Student to GradeEntry, so I suspected getGrades was actually returning Students and yes that is the case:
public ArrayList<Student> getGrades() {
return students; //this part is a problem.
}
I think you meant to return grades:
public ArrayList<Grade> getGrades() {
return gr;
}