I am trying to reverse a linked list in Java using stack I keep on receiving this error:
LinkStackApp.java:84: error: constructor LinkStack in class LinkStack cannot be applied to given types;
LinkStack stackrev = new LinkStack(stackSize);
^
required: no arguments
found: int
reason: actual and formal argument lists differ in length
1 error
I don't know where it finds int, I tried changing the Strings to char and vice versa but just keep on getting more errors any ideas? here is my full code:
import java.io.*;
import java.util.Scanner;
class Link
{
public char dData;
public Link next;
public Link(char dd)
{
dData = dd;
}
public void displayLink()
{
System.out.print(dData + " ");
}
}
class LinkList
{
private Link first; //ref to first item on the list
public LinkList() //no items on list yet
{
first = null;
}
public boolean isEmpty()
{
return (first == null);
}
public void insertFirst(char dd)
{
Link newLink = new Link(dd);
newLink.next = first;
first = newLink;
}
public char deleteFirst()
{
Link temp = first;
first = first.next;
return temp.dData;
}
public void displayList()
{
Link current = first;
while(current != null)
{
current.displayLink();
current = current.next;
}
System.out.println(" ");
}
}
class LinkStack
{
private LinkList theList;
public LinkStack()
{
theList = new LinkList();
}
public void push(char j)
{
theList.insertFirst(j);
}
public char pop()
{
return theList.deleteFirst();
}
public boolean isEmpty()
{
return (theList.isEmpty());
}
}
class Reverser{
private String input;
private String output;
public Reverser(String in){
input = in;
}
public String doRev(){
int stackSize = input.length();
LinkStack stackrev = new LinkStack(stackSize);
for (int j = 0; j <input.length(); j++){
char ch = input.charAt(j);
stackrev.push(ch);
}
output = "";
while(!stackrev.isEmpty()){
char ch = stackrev.pop();
output = output + ch;
}
return output;
}
}
class LinkStackApp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String inputString, outputString;
while(true){
System.out.print("Enter A String: ");
inputString = input.nextLine();
if(inputString.equals(""))
break;
Reverser therev = new Reverser(inputString);
outputString = therev.doRev();
System.out.println("Reversed: "+outputString);
}
}
}
stackSize is an int. It's telling you to call the constructor with no params.
The correct constructor invocation is:
LinkStack stackrev = new LinkStack();
Related
This question already has answers here:
this: Cannot use this in static context
(5 answers)
Closed 1 year ago.
I am implementing my own generic Linked List class and it has a instance method called toArray that make a array copy of the linked list and return it. However, whenever I try to call that method on an instance I keep getting error message "SLList.this cannot be referenced from a static context". I searched for it for a bit and some people said that it was because I did not call that method on an instance, but I indeed did.
Here is the class:
public class SLList<ElemType>{
private class StuffNode{
public ElemType item;
public StuffNode next;
public StuffNode(ElemType i, StuffNode n){
item = i;
next = n;
}
}
/** The first item of a list(if it exists) is at sentinel.next*/
private StuffNode sentinel;
private int size;
public ElemType[] toArray(){
ElemType[] arr =(ElemType[]) new Object[this.size];
StuffNode ptr = this.sentinel;
int i = 0;
while(ptr.next != null){
arr[i] = ptr.next.item;
ptr = ptr.next;
i++;
}
return arr;
}
}
It has some method like addLast, addFirst and they have no problem.
public static void main(String[] args){
SLList<Integer> x = new SLList<>(3);
x.addLast(4);
x.addFirst(1);
ElemType[] arr = x.toArray();
}
ElemType[] arr = x.toArray(); is the line where I keep getting error message, and I have used a online Java visualizer to confirm that method works just fine, I just have problem returning the result from it
You could do it like this:
public class Main2 {
public static void main(String[] args) {
SLList<Integer> x = new Main2().new SLList<>(3);
x.addLast(4);
x.addFirst(1);
Integer[] arr = x.toArray();
}
public class SLList<ElemType> {
private class StuffNode {
public ElemType item;
public StuffNode next;
public StuffNode(ElemType i, StuffNode n) {
item = i;
next = n;
}
}
public SLList(ElemType n) {
// Some code for constructor
}
public void addFirst(ElemType n) {
// Some code
}
public void addLast(ElemType n) {
// Some code
}
/**
* The first item of a list(if it exists) is at sentinel.next
*/
private StuffNode sentinel;
private int size;
public ElemType[] toArray() {
ElemType[] arr = (ElemType[]) new Object[this.size];
StuffNode ptr = this.sentinel;
int i = 0;
while (ptr.next != null) {
arr[i] = ptr.next.item;
ptr = ptr.next;
i++;
}
return arr;
}
}
}
or like this:
public class Main2 {
public static void main(String[] args) {
SLList<Integer> x = new SLList<>(3);
x.addLast(4);
x.addFirst(1);
Integer[] arr = x.toArray();
}
// INSERT A STATIC HERE
public static class SLList<ElemType> {
private class StuffNode {
public ElemType item;
public StuffNode next;
public StuffNode(ElemType i, StuffNode n) {
item = i;
next = n;
}
}
public SLList(ElemType n) {
// Some code for constructor
}
public void addFirst(ElemType n) {
// Some code
}
public void addLast(ElemType n) {
// Some code
}
/**
* The first item of a list(if it exists) is at sentinel.next
*/
private StuffNode sentinel;
private int size;
public ElemType[] toArray() {
ElemType[] arr = (ElemType[]) new Object[this.size];
StuffNode ptr = this.sentinel;
int i = 0;
while (ptr.next != null) {
arr[i] = ptr.next.item;
ptr = ptr.next;
i++;
}
return arr;
}
}
}
I am working on an assignment and I can not figure out what to do. I have three different Java classes. And I am trying to use the methods in one class to do something in a different class. I am making a very primitive playlist program. I have to check to see if the playlist is full, if its not i have to ask the title and artist. Then I have to call my method using the title and artist as parameters. I was wondering if anyone could point me in the right direction as to what I had to do to call the method? I still don't completely understand loops either but i know that I have to use a for loop in order to do this. Thankyou for your time.
Here is my code:
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to
quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
for (int i = 0; i <= PlayList.isFull(title, artist);i++) {
if(songs[i])== null {
songs[i] = filled;
}
}
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to
quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
public class PlayList {
private Song [] songs;
private int filled;
public PlayList (int size){
songs = new Song[size];
}
public boolean isFull() {
return (filled >= songs.length);
}
public void add(String t, String a) {
for (int i = 0; i < songs.length; i++){
if (songs[i] == null){
songs[i] = new Song(t,a);
filled++;
}
}
}
public void display() {
for (int i = 0; i < songs.length; i++){
if (songs[i] != null) {
System.out.println(songs[i]);
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.length; i--){
if (songs[i] == null){
songs[i] = null;
break;
}
}
}
}
Song Class
public class Song {
String title;
String artist;
public Song (String t, String a) {
title = t;
artist = a;
}
public String toString() {
return "Title: " + title + " " + "Artist: " + artist;
}
}
First of all you are using isFull function of class PlayList wrong.
for (int i = 0; i <= PlayList.isFull(title, artist);i++)
isFull is a no argument function, and you are using it with passing 2 arguments.
isFull function returns a boolean value (i.e. true/false), but you are comparing it with an int, which does not make any sense.
isFull is not a static function. Therefore you cannot use it directly with class name.
-either you will need to declare function isFull as static.
public static boolean isFull()
-or you will need to create an object of class PlayList in class Main and then call the java function using that java object.
Also, your Function remove is not performing any task
if (songs[i] == null){
songs[i] = null;
}
It is checking if songs[i] is already null and then it sets it back to null, which does not make any sense.
And you should increment i (i.e. i++) not decrement it (i.e. i--)
for (int i = 0; i < songs.length; i--)
If you want to call method from another class that method must be a static method. Then you can call it using Class name and Method name.
For an example;
public class main(){
A a = new A();
a.x();
}
public class A{
public static void x(){};
}
You called isFull method with two parameters but your PlayList class does not have any parameter for isFull method. That is an error.
I re-write your assignment class set using ArrayList for PlayList class. Follow this codes. Hope you can understand it's concept of OOP(Follow this tutorials. https://www.javatpoint.com/java-oops-concepts).
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
System.out.println("Enter Title:");
title = sc.nextLine();
System.out.println("Enter Artist:");
artist = sc.nextLine();
if(!p.isFull()) {
p.add(title, artist);
System.out.println("Added Success!");
}
else
System.out.println("Sorry,Playlist is full");
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
p.display();
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
import java.util.ArrayList;
import java.util.List;
public class PlayList {
private static List<Song> songs;
private static int filled;
private static int size = 0;
public PlayList (int s){
songs = new ArrayList<>();
size = s;
}
public static boolean isFull() {
return (filled == size);
}
public static void add(String t, String a) {
songs.add(new Song(t,a));
filled++;
}
public void display() {
for (int i = 0; i < songs.size(); i++){
if (songs.get(i) != null) {
System.out.println(songs.get(i));
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.size(); i++){
if (songs.get(i).title == t){
songs.remove(i);
break;
}
}
}
public static int getSize(){
return songs.size();
}
}
Song Class is same as you wrote.
How would i make a while loop to go through the characters of the Strings of text to find the first place there is a blank and returning the value of the position. I do i need a double condition in the while loop?
public class TestSentenceCounter
{
private static final String SENTENCE1 = "This is my sentence.";
private static final String SENTENCE2 = "These words make another sentence that is longer";
private SentenceCounter sc1;
private SentenceCounter sc2;
/**
* Create two instances we can play with
*/
#Before
public void setup()
{
sc1 = new SentenceCounter(SENTENCE1);
sc2 = new SentenceCounter(SENTENCE2);
}
/**
* Make sure the instance variable is correct
*/
#Test
public void testConstructor()
{
assertEquals(SENTENCE1, sc1.getSentence());
assertEquals(SENTENCE2, sc2.getSentence());
}
#Test
public void testFirstBlankPosition()
{
assertEquals(4, sc1.firstBlankPosition());
assertEquals(5, sc2.firstBlankPosition());
}
}
----------------------------------------------------
public class SentenceCounter
{
public String sentence;
public SentenceCounter(String sentence)
{
this.sentence = sentence;
}
public Object getSentence()
{
return sentence;
}
public Object firstBlankPosition()
{
return null;
}
}
Update your code accordingly ,
public int firstBlankPosition()
{
int returnVal = 0;
char ch ;
for(int i = 0 ; i < sentence.length() ; i++){
ch = sentence.charAt(i);
if(ch == ' '){
returnVal = i;
break;
}
}
return returnVal;
}
I created my own linked list, but when I tried to run it there is an error:
Exception in thread "main" java.lang.NullPointerException
at List.add(List.java:8) //if(t.val ==null)
at main.main(main.java:38) //linput.add(inputLine.split(" ")[i]);
Here is my List class:
class List{
String val;
List next=null;
private List t;
public void add(String word){
if(t.val ==null)
t.val=word;
else while(!t.next.val.equals(null))
{
t=t.next;
if(t.next.val.equals(null))
{
t.next.val=word;
break;
}
}
}
public int get(String word)
{
int i=0;
if(t.val.equals(word))
i=0;
else while(!t.next.val.equals(word))
{
t=t.next;
i++;
if(t.next.val.equals(word))
{
i++;
}
}
return i;
}
public String indexOf(int i)
{
int counter=0;
while(counter<i)
{
t=t.next;
counter++;
}
return t.val;
}
}
And here is my main function :
static public void main(String[] args)
{
List linput = new List();
String inputLine = "Hey look at me.";
for(int i = 0 ; i < inputLine.split(" ").length ; i++)
{
linput.add(inputLine.split(" ")[i]);
}
System.out.println(linput.indexOf(0)+" "+linput.indexOf(1)+" "+linput.indexOf(2));
}
I initialized t but next time there is an error like this:
private List t =new List();
Exception in thread "main" java.lang.StackOverflowError
at List.<init>(List.java:5)
at List.<init>(List.java:5)
at List.<init>(List.java:5)
Sorry. I can't give my full code, because the rest of my code is working well (reading from txt etc....).
The error seems to be related to the variable 't' (i.e., private List t).
Did you initialize this variable ? The if (t.val == null) seems to be cribbing this as t is null (uninitialized) at this point
You should have allocated object (using new) for this variable.
Can you share the full code for the constructor of List ?
Assuming you want to implement a simple forward list, rather than use the Java LinkedList class, you need to:
Change your implementation of the list to reference nodes in the list
handle traversal of the linked nodes in your word list
Here is an example:
WordList class
package com.example.words;
class WordList {
private WordNode head = null;
private int listSize = 0;
public void add(String word) {
// TODO add check for duplicate word
if (head == null) {
head = new WordNode();
head.setValue(word);
listSize++;
} else {
WordNode current = head;
while (current.getNext() != null) {
current = current.getNext();
}
WordNode newNode = new WordNode();
newNode.setValue(word);
current.setNext(newNode);
listSize++;
}
}
public int getWordIndex(String word) {
WordNode current = head;
int index = 0;
boolean found = false;
while (!found && current != null) {
found = current.getValue().equalsIgnoreCase(word);
if (!found) {
index++;
current = current.getNext();
}
}
if (found) {
return index;
} else {
return -1;
}
}
public String indexOf(int i) {
int index = 0;
WordNode current = head;
if (i <= listSize) {
while (index < i) {
current = current.getNext();
index++;
}
return current.getValue();
} else {
return null;
}
}
public int size() {
return listSize;
}
}
WordNode Class
package com.example.words;
public class WordNode {
private String value;
private WordNode next = null;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public WordNode getNext() {
return next;
}
public void setNext(WordNode link) {
next = link;
}
}
Test Driver
package com.example.words;
public class Test {
public static void main(String[] args) {
//TODO handle punctuation
WordList myList = new WordList();
String inputLine = "Hey look at me.";
String[] pieces = inputLine.split(" ");
for (int i=0; i < pieces.length; i++) {
myList.add(pieces[i]);
}
for (int i=0; i < pieces.length; i++) {
String value = myList.indexOf(i);
if (value.equalsIgnoreCase(pieces[i])) {
System.out.println("Following node is wrong:");
}
System.out.println ("node " + i + ". = " + value);
}
}
}
You tried to create t as a member variable of its own class like this:
class List {
[...]
private List t = new List();
[...]
}
This won't work because the constructor of List would be called indefinitely.
Try lazy instantiation of t instead. Replace all access of t with a getter:
private List getT() {
if (this.t == null) {
this.t = new List();
}
return t;
}
I'm trying to access the method changeAll from class MarkMaker the following way:
import java.util.Scanner;
class Question10e
{
public static void main(String[] args)
{
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Enter mark 1: ");
int newm1=input.nextInt();
System.out.print("Enter mark 2: ");
int newm2=input.nextInt();
System.out.print("Enter mark 3: ");
int newm3=input.nextInt();
String linem=input.nextLine();
System.out.print("Enter a master password: ");
String masterpass = input.next();
linem=input.nextLine();
MarkMaker mm = new MarkMaker(masterpass);
Mark masterMark1 = mm.makeMark(newm1);
Mark masterMark2 = mm.makeMark(newm2);
Mark masterMark3 = mm.makeMark(newm3);
try{
System.out.println("The new mark 1 is "+masterMark1.provisional(masterpass));
System.out.println("The new mark 2 is "+masterMark2.provisional(masterpass));
System.out.println("The new mark 3 is "+masterMark3.provisional(masterpass));
System.out.println("The new master password is is "+masterMark1.returnPass());
int avg = mm.average();
System.out.println("The average is "+avg);
changeAll(5.5, 3);
}
catch(IncorrectPasswordException e){}
}
}
This is the MarkMaker class:
import java.util.*;
class MarkMaker{
private String masterPass = "";
private ArrayList<Mark> masterArr = new ArrayList<Mark>();
public MarkMaker(String masterPass)
{
this.masterPass = masterPass;
}
public Mark makeMark(int m)
{
Mark newMarkObj = new Mark(m,masterPass);
masterArr.add(newMarkObj);
return newMarkObj;
}
public ArrayList<Mark> returnMasterArr()
{
return masterArr;
}
public int average() throws IncorrectPasswordException
{
int n = 0;
for(int i=0; i<masterArr.size(); i++)
{
n = n + masterArr.get(i).provisional(masterPass);
}
int avg = n/masterArr.size();
return avg;
}
public void changeAll(double d, int x) throws IncorrectPasswordException
{
for(int i=0; i<masterArr.size(); i++)
{
double currentMark = masterArr.get(i).provisional(masterPass);
System.out.println("Current mark is: "+currentMark);
currentMark = currentMark*d;
System.out.println("Current mark is: "+currentMark);
currentMark = Math.ceil(currentMark);
System.out.println("Current mark is: "+currentMark);
}
} }
And this is the Mark class:
class Mark
{
private int value;
private String password;
boolean released;
public Mark(int value, String password)
{
this.value = value;
this.password = password;
released = false;
}
public void release(String p) throws IncorrectPasswordException
{
if(p.equals(password))
{
if(released==false)
released = true;
}
else throw new IncorrectPasswordException(p);
}
public int value() throws UnReleasedException
{
if(released==true)
return value;
else
throw new UnReleasedException();
}
public int provisional(String p) throws IncorrectPasswordException
{
if(p.equals(password))
return value;
else
throw new IncorrectPasswordException(p);
}
public void change(String p, int arg) throws IncorrectPasswordException
{
if(p.equals(password))
value = arg;
else
throw new IncorrectPasswordException(p);
}
public String returnPass()
{
return password;
}
public boolean isReleased()
{
return released;
}
public boolean equals(Mark m2) throws UnReleasedException
{
if(this.isReleased() && m2.isReleased())
{ //it throws an error, that's why i'm using the Unreleased Exception
if(this.value()==m2.value())
return true;
}
throw new UnReleasedException();
} }
The problem is that I always get a "cannot find symbol error - method changeAll(double, int), location class Question10e"
Question10e doesn't have this method. Perhaps you intended to call this on an instance of a class which does like.
mm.changeAll(5.5, 3);
changeAll is a method which belongs to the MarkMaker class rather than the current Question10e class where you are attempting to call the method:
mm.changeAll(5.5, 3);
You need to call changeAll() through a MarkMarker object. It doesn't exist in your Question10e class. So, you could do this by:
mm.changeAll(5.5, 3)
Just because changeAll() is public doesn't mean that you can call it from anywhere. It simply means that a MarkMarker object can call it from anywhere.
You need
mm.changeAll(5.5, 3);