How to fix java error? - java

So I have to create a program where I use polymorphism and inheritance to create arrows that point left and arrow and I did that. however, when I created my main class and try to invoke the methods, say for example "LeftArrow.drawHere" to draw the arrow i get errors saying I cannot make a static reference to the non static field "drawHere() from the class LeftArrow". I was wondering then if I can't do that how can I design my main method so it draws the arrows?
here is my code, note that there are several classes but I will post all of them here.
import java.util.Scanner;
public class LeftArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public LeftArrow()
{
super();
tail = 0;
width = 0;
}
public LeftArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth);
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
//System.out.println();
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset());
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside + 1));
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawTail()
{
skipSpaces(getOffset() - getInside() - 1);
System.out.print('*');
skipSpaces(getInside());
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside - 1));
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset());
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
#Override
public void setOffset(int noff) {
// TODO Auto-generated method stub
}
#Override
public int getOffset() {
// TODO Auto-generated method stub
return 0;
}
}
import java.util.Scanner;
public class RightArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public RightArrow()
{
super();
tail = 0;
width = 0;
}
public RightArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth); // must be odd
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
System.out.println();
}
public void drawTail()
{
skipSpaces(getOffset() + 1);
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
skipSpaces(getInside());
System.out.print('*'); // fix
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset() + tail);
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset() + tail);
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
}
public abstract class ShapeBase implements ShapeInterface {
private int offset;
public abstract void drawHere();
public void drawAt(int lineNumber) {
for (int count = 0; count < lineNumber; count++)
System.out.println();
drawHere();
}
}
public class ShapeBasic implements ShapeInterface
{
private int offset;
public ShapeBasic()
{
offset = 0;
}
public ShapeBasic( int noff)
{
offset = noff;
}
public void setOffset(int noff)
{
offset = noff;
}
public int getOffset()
{
return offset;
}
public void drawAt(int linnumber)
{
for (int count = 0; count < linnumber; count++)
System.out.println();
drawHere();
}
public void drawHere()
{
for (int count = 0; count < offset; count++)
System.out.print(' ');
System.out.println('*');
}
}
public interface ShapeInterface
{
public void setOffset(int noff); // set how many space from left
public int getOffset(); // returns offset
public void drawAt(int linnumber); // moves down equal to line number Ex. 5 = 5 down
public void drawHere(); // draws shape after moving left equal to offset
}

I'd ask to see your main method, but I don't have the reputation.
At a guess, I'd say maybe you are not actually instantiating objects of these classes in your main method, but trying to call the methods from them. If, for instance, you do this:
LeftArrow lArrow = new LeftArrow();
lArrow.drawHere();
it should work.

The method drawHere is declared as non-static. Instead of LeftArrow.drawHere() you should call
LeftArrow left = new LefArrow(a, b, c);
left.drawHere();

main is static. It needs to create instances of LeftArrow before it can use them. Something like this:
LeftArrow myArrow = new LeftArrow();
myArrow.drawHere();

Related

Wrong amount of lines in printTriangle?

I've been doing a MOOC.fi Java course and it comes along quite well, except the Christmas Tree part. It works as intended in the output, but the system won't accept it and I don't know why.
I get this error:
when printTriangle(1) was called, wrong amount of lines was printed expected:<1> but was:<2>
Here's the code:
public class AdvancedAstrology {
public static void printStars(int number) {
for(int i = 0; i < number; i++){
System.out.print("*");
}
System.out.println();
}
public static void printSpaces(int number) {
while(number > 0){
System.out.print(' ');
number--;
}
}
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++);
}
}
public static void christmasTree(int height) {
int h = height -1;
int stand = height - 2;
int s = 1;
while(height > 0){
printSpaces(h);
printStars(s);
s+=2;
h--;
height--;
}
printSpaces(stand);
printStars(3);
printSpaces(stand);
printStars(3);
}
public static void main(String[] args) {
// The tests are not checking the main, so you can modify it freely.
printTriangle(5);
System.out.println("---");
christmasTree(4);
System.out.println("---");
christmasTree(10);
}
}
You're doing post increment, that's why in star is being passed as 0 in first iteration.
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++); //Here. change it to ++star
}
}

Selection Sort not sorting Java

I am working on a selection sort in Java. It will prompt a user to enter in 10 names and then sort them alphabetically. It is sorting some of them but not completely and cannot figure out why it is sorting some values and not others. I believe I have implemented the sort and swap correctly but I feel as though I am missing something. Any help is appreciated as always.
import java.util.*;
public class sortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
You are doing your swap too early. You need to wait until the smallest has been determined before swapping. You are swapping whenever you detect a smaller one.
public static void sortNames(String sortArray[]) {
for (int i = 0; i < sortArray.length; i++) {
int smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
// Move this.
//if (smallindex != i)
// swap(sortArray, smallindex, i);
}
}
// To here.
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
private void test() {
String[] names = {"C", "B", "A", "9"};
System.out.println(Arrays.toString(names));
sortNames(names);
System.out.println(Arrays.toString(names));
}
use below changes in your program.
import java.util.*;
public class SortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
//if (smallindex != i) No need here
//swap(sortArray, smallindex, i);
}
}
//place your swaping code here
if (smallindex != i)
swap(sortArray, smallindex, i);
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
after making these changes your program works. your code not works properly because you perform swap early.

Why the program is not showing any output?

I have been trying to troubleshoot this java program from hours now and has not been able to find what is wrong with the execution. I think that the main class is not defined correctly.
It compiles successfully but the output is blank which should not be the case right? I intially tried to call the main class using the objects but still no luck. Any suggestions will work.
The original program:It compiles successfully on adding the main method but the output is blank.
import java.lang.Math; // headers MUST be above the first class
// one class needs to have a main() method
public class OrdSetSimple
{
// arguments are passed using the text field below this editor
public static void main(String[] args){
OrdSetSimple obj = new OrdSetSimple(10);
System.out.print("Success");
}
private int _set_size;
private int _set[];
private int _last;
public OrdSetSimple(int size) {
int k;
_set_size=size;
_set = new int[_set_size];
for(k=0; k<_set_size; k++)
_set[k]=0;
_last=-1;
}
private int make_a_free_slot(int val) {
int pos, i, j;
pos = binSearch(val);
if (pos >= 0)
return -1;
for (i=0; i<=_last; i++) {
if (_set[i] > val)
break;
}
if ((i<=_last)||(_last==-1)) {
for (j=_last; j>=i; j--)
_set[j+1] = _set[j];
pos = i;
} else {
pos = _last+1;
}
_last++;
return pos;
}
public void addElement(int n) {
int pos;
if (n<0) {
System.out.println("Addition of a negative integer impossible\n");
return;
}
if (_last+1>=_set_size) {
System.out.print("Addition of " + n);
System.out.println(" impossible since the array is already full");
System.out.println("The array is: " + toString());
} else {
pos = make_a_free_slot(n);
if (pos>=0)
_set[pos]=n;
}
return;
}
public int getSize() {
return _last+1;
}
public int getElementAt(int i) {
if ((i<0)||(i>_last))
return -1;
else
return _set[i];
}
private int binSearch(int x) {
int i=0;
int j=_last-1;
int m=0;
if (_last==-1)
return -1;
while(i<j) {
m= (i+j)/2;
if (x>_set[m])
i=m+1;
else
j=m;
}
if (x == _set[i]) return i;
else return -1;
}
public OrdSetSimple difference(OrdSetSimple s2) {
OrdSetSimple s1 = this;
int size1=s1.getSize();
int size2=s2.getSize();
OrdSetSimple set=new OrdSetSimple(size2);
int k;
for(k=0; k<size1; k++)
if (s2.binSearch(s1.getElementAt(k)) < 0)
set.addElement(s1.getElementAt(k));
return set;
}
public String toString() {
int k = 0;
String s="";
for (k=0; k<=_last; k++)
s += _set[k] + " ";
return s;
}
}
Your very first statement is wrong.
OrdSetSimple obj = new OrdSetSimple();//This will call the default constructor which will not initialize anything. This constructor will be added to your program by compiler, hence you don't get any compilation error.
Correct it like
OrdSetSimple obj = new OrdSetSimple(100);

Creating a new array element copies to the array index below it [closed]

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
When I create a new array element, it gets stored into the array index, then the array index increments to the next.
However, I am getting a different result. The array element copies down to all previous array indexes.
import java.util.Scanner;
import java.io.*;
public class VectorOfContacts implements ProjTwo
{
private int size;
private int capacity;
private int incrementCapacity;
Contact[] contacts;
File file = new File("contacts.txt");
Scanner input = new Scanner(System.in);
public VectorOfContacts()
{
size = 0;
capacity = 10;
incrementCapacity = capacity;
contacts = new Contact[capacity];
}
public int getSize()
{
return size;
}
public int getCapacity()
{
return capacity;
}
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
//public VectorOfContacts(int inCapacity)
//{
//inCapacity = 100;
//incrementCapacity = inCapacity;
//}
public void readInitialFromFile()
{
Contact c = new Contact();
String temp = null;
try{
Scanner input = new Scanner(file);
for (int i = 0 ; i < size; i++)
{
temp = input.nextLine();
String[] part = input.nextLine().split(":");
System.out.println(part);
String name = part[0];
long number = Long.parseLong(part[1]);
String comment = part[2];
c.setName(name);
c.setPhoneNumber(number);
c.setComment(comment);
contacts[i] = c;
contacts[size] = contacts[i];
}
input.close();
}catch(FileNotFoundException e){
System.out.println("File not found.");
System.exit(0);
}
}
public void writeFinalToFile()
{
try{
PrintWriter output = new PrintWriter(file);
for (int i = 0; i < size; i++)
{
output.println(contacts[i]);
}
output.close();
}catch(FileNotFoundException a){
System.out.println("Something is wrong.");
System.exit(0);
}
System.exit(0);
}
public void addContact(Contact c)
{
addElement(c);
}
public void deleteContact(String nm)
{
System.out.println("Delete which name?");
nm = input.nextLine();
for(int i = 0; i < size; i++)
{
if(contacts[i].getName() == nm);
{
contacts[i] = contacts[i+1];
}
}
System.out.println("Deletion confirmed");
}
public void showByName(String nm)
{
nm = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (nm.startsWith(contacts[i].getName()))
{
System.out.println(contacts[i]);
}
}
}
public void showByPhoneNumber(long pN)
{
pN = input.nextLong();
for ( int i = 0; i < size; i++)
{
if (contacts[i].getPhoneNumber() == pN)
{
System.out.println(contacts[i]);
}
}
}
public void showByComment(String c)
{
c = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (c.startsWith(contacts[i].getComment()))
{
System.out.println(contacts[i]);
}
}
}
public boolean isFull()
{
if (size == capacity)
{
return true;
}
else
{
return false;
}
}
public boolean isEmpty()
{
if (size == 0)
return true;
else
return false;
}
public void addElement(Contact item)
{
if (isFull() == true)
incrementCapacity();
contacts[size] = item;
size++;
System.out.println("size" + size);
for (int i = 0; i < size; i++)
{
System.out.println(contacts[i]);
}
}
public void incrementCapacity()
{
Contact[] temp_contacts = new Contact[capacity + incrementCapacity];
for(int i = 0; i < size; i++)
{
temp_contacts[i] = contacts[i];
}
capacity = capacity + incrementCapacity;
contacts = temp_contacts;
}
}
These are the end results
size1
test:1234:1
size2
no:5555:2
no:5555:2
size3
jaja:1666:test
jaja:1666:test
jaja:1666:test
You print one object for all indexes, you need to use next:
for (int i = 0; i < size; i++){
System.out.println(contacts[i]);
}
You could improve a lof of things.
Don't expose everything as public
The class VectorOfContacts does a lot of things. You should split it into many classes.
Use the Java Framework (Array.copy(), ArrayList, ...)
Don't do if (true) return true else return false
Write tests
In readInitialFromFile you're creating the contact outside of the loop. So you reusing the same object of all contacts.
Those setters dont do anything, you missing an argument. But they shouldn't be public anyway so you don't need them.
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
isFull and isEmpty shouldn't be public and can be a lot shorter
private boolean isFull() {
return size == capacity;
}
private boolean isEmpty() {
return size == 0;
}
Please clean up your code first.

Java - swap arraylist index

I made a map by arraylist, and trying to swap the index(not the value) of arraylist.
For example, the swapRow(1,2) changes the position of row 1 and 2.
This works at the first time, but if I do it again, an error comes out.(Same problem with the swapCol() part.)
Stuck in this problem and need help...
In addition, can anyone help me out making the swapValue() method.
Changing the value is simple, though I also want to move the index, not the value.
import java.text.DecimalFormat;
import java.util.ArrayList;
public class IntMap {
class Data {
private int data_;
public Data(int data)
{
setData(data);
}
public void setData(int data)
{
if(data<0)data=0;
if(data>99)data=99;
data_=data;
}
public int getData()
{
return data_;
}
}
class Index {
private int index_;
public Index(int index)
{
setIndex(index);
}
public void setIndex(int index)
{
if(index < 0) index=0;
index_=index;
}
public int getIndex()
{
return index_;
}
}
private ArrayList<ArrayList<Data>> datas_;
private ArrayList<Index> cols_;
private ArrayList<Index> rows_;
public IntMap(int rowCount, int colCount)
{
if(rowCount < 0) rowCount = 1;
if(rowCount < 0) colCount = 1;
cols_ = new ArrayList<Index>();
rows_ = new ArrayList<Index>();
datas_ = new ArrayList<ArrayList<Data>>();
for(int i=0 ; i<rowCount ; ++i) rows_.add(new Index(i));
for(int i=0 ; i<colCount ; ++i) cols_.add(new Index(i));
for(int i=0 ; i< rowCount ; ++i)
{
ArrayList<Data> temp = new ArrayList<Data>();
datas_.add(temp);
for(int j=0 ; j<colCount ; ++j)
{
temp.add(new Data(0));
}
}
}
public int getValue(int row, int col)
{
int rIndex = getRowIndex(row);
int cIndex = getColIndex(col);
return datas_.get(rIndex).get(cIndex).getData();
}
public void setValue(int row, int col, int value)
{
int rIndex = getRowIndex(row);
int cIndex = getColIndex(col);
datas_.get(rIndex).get(cIndex).setData(value);
}
public void setRandomValue()
{
for(int row=0 ; row < datas_.size() ; ++row)
{
ArrayList<Data> temp = datas_.get(row);
for(int col=0; col <temp.size() ; ++col)
{
Data data = temp.get(col);
data.setData((int)(Math.random()*100));
}
}
}
public void log()
{
DecimalFormat df = new DecimalFormat("00");
for(int row=0; row<rows_.size(); ++row)
{
for(int col=0; col<cols_.size(); ++col)
{
int value = getValue(row, col);
System.out.print(df.format(value));
if(col<cols_.size()-1)
System.out.print(", ");
}
System.out.println();
}
System.out.println();
}
private int getColIndex(int col)
{
if(col <0 || col>=cols_.size())
{
System.out.println("[error][IntMap][getColIndex] - col is"+col);
return 0;
}
for(int i =0; i<cols_.size(); ++i)
{
if(cols_.get(i).getIndex()==col)
return i;
}
System.out.println("[error][IntMap][getColIndex] - unknown error");
return 0;
}
private int getRowIndex(int row)
{
if(row <0 || row>=rows_.size())
{
System.out.println("[error][IntMap][getRowIndex] - row is"+row);
return 0;
}
for(int i =0; i<rows_.size(); ++i)
{
if(rows_.get(i).getIndex()==row)
return i;
}
System.out.println("[error][IntMap][getRowIndex] - unknown error");
return 0;
}
public void swapValue(int a, int b, int c, int d)
{
//
}
public void swapCol(int a, int b)
{
int col1=a;
int col2=b;
int t=a;
cols_.get(col1).setIndex(col2);
cols_.get(col2).setIndex(t);
}
public void swapRow(int a, int b)
{
int t=a;
rows_.get(a).setIndex(b);
rows_.get(b).setIndex(t);
}
public static void main(String[] args)
{
System.out.println("start!");
IntMap map =new IntMap(3,4);
System.out.println("Init map 3x4");
map.log();
System.out.println("random map");
map.setRandomValue();
map.log();
System.out.print("get map[0][1]= ");
System.out.println(map.getValue(0,1));
System.out.println("set map[2][1]=50");
map.setValue(2, 1 ,50);
map.log();
System.out.println("swap(0,1 <-> 2,1)");
map.swapValue(0,1,2,1);
map.log();
System.out.println("swapRow(0 <-> 2)");
map.swapRow(0,2);
map.log();
System.out.println("swapRow(1 <-> 2)");
map.swapRow(1,2);
map.log();
System.out.println("swapCol(0 <-> 3)");
map.swapCol(0,3);
map.log();
}
}
I think you got confused the index of rows_ arrayList and your Index type. your swapRow(a,b) should check rows_ list and find out the element (Index Object) .getIndex = a and b, then swap the two Index elements, not just like what you did in your method. If you change the method into followings, it should work. you could do some error handling, e.g. what happend parameter a or b invalid. I just set themt to 0.
public void swapRow(int a, int b) {
int ai = 0, bi = 0;
for (final Index i : rows_) {
if (i.getIndex() == a) {
ai = rows_.indexOf(i);
}
if (i.getIndex() == b) {
bi = rows_.indexOf(i);
}
}
final Index aidx = rows_.get(ai);
rows_.set(ai, rows_.get(bi));
rows_.set(bi, aidx);
}
and, i don't know your exact requirment. but from the design point of view, there might be room to improve.

Categories