How do you print a stack in Java? [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
I have tried many different things to try to print this stack but it keeps printing the hashcode ie. Problem1$Node#3d4eac69. I have searched a lot online and found nothing that has worked for this so if there are any suggestions help is greatly appreciated.
import java.util.*;
public class Problem1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Reading the first integer containing the number of test queries
int N = input.nextInt();
// Initializing the maximum value
int max = Integer.MIN_VALUE;
// Initializing the stack.
Stack<Node> stack = new Stack<Node>();
// Read the query and perform the actions specified.
for(int i = 0; i < N; i++){
int x = input.nextInt();
if(x == 1){
int value = input.nextInt();
Node n = new Node(value);
stack.push(n);
System.out.println(stack);
}
else if(x == 2){
stack.pop();
}
else if(x == 3){
System.out.println(stack.peek());
}
}
}
static class Node{
int data;
public Node(int data){
this.data = data;
}
}
}

You need to override the default toString method (inherited from Object see API here ) in your Node class, something like this:
static class Node {
int data;
public Node(int data){
this.data = data;
}
#Override
public String toString() {
return "Node: "+data;
}
}
The toString method is used when you try to print the object as a String. If you don't have one, it will use the Object's one which builds a String this way
getClass().getName() + '#' + Integer.toHexString(hashCode()))
and gives you something like Problem1$Node#3d4eac69

Related

Null pointer Exception even though setter method is present in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I wrote a code for keeping record of indices even after sorting but it is showing me null pointer exception.I read other threads on same topic but still couldn't find.
import java.io.*;
import java.util.*;
public class Solution {
class Order{
public int index;
public int sum;
public void setIndex(int index){
this.index = index;
}
public void setSum(int sum){
this.sum = sum;
}
public int getSum(){
return this.sum;
}
public int getIndex(){
return this.index;
}
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
Order array[] = new Order[N];
int index = 0;
int sum = 0;
while(index<N){
int input1 = sc.nextInt();
int input2 = sc.nextInt();
//line 32
array[index].setIndex(index);
array[index].setSum(input1+input2);
index++;
}
ArrayList<Order> list = new ArrayList<Order>(Arrays.asList(array));
Collections.sort(list, new Comparator<Order>(){
#Override
public int compare(Order o1, Order o2){
return(Integer.compare(o1.getSum(), o2.getSum()));
}
});
System.out.println(list);
}
}
error is like this :
Exception in thread "main" java.lang.NullPointerException
at Solution.main(Solution.java:32)
I am passing i, still null pointer why?
You initialized array with Order array[] = new Order[N];, but the array is full of null objects. You need to initialize every element with new Order and then use setters

Reversing a String using a LinkedList based Stack [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 5 years ago.
Improve this question
The assignment given to me is this: Create an application to reverse a list by using a linked list based Stack data structure. When you run the program, it asks you to type in an input. When you press Enter, it displays the input in reverse order. You decide the input data type this time.
I made my Node class or Link class, my LinkedList class, LinkedListStack Class, and now i am stuck in the main method.I posted all of my code below in hopes of someone helping me find the error I am making. I looked at other posts but most of them deal with either just reversing a linked list alone, a string, or a linkedlist arraylist.
This is the error I keep getting:
Please enter a word: Hello
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at LinkedStackDemo.main(LinkedStackDemo.java:32)
public class Node
{
public String data;
public Node next;
public Node(String d)
{
data = d;
}
public void displayNode()
{
System.out.println(data + " ");
}
}
Linked List Class
public class LinkedList
{
public Node first;
public LinkedList()
{
first = null;
}
public boolean isEmpty()
{
return (first == null);
}
public void insertFirst(String d)
{
Node n = new Node(d);
n.next = first;
first = n;
}
public String deleteFirst()
{
//if(first == null)
//{return first;}
Node temp = first;
first = first.next;
//temp.next = null;
//return temp;
return temp.data;
}
public void displayNode()
{
Node current = first;
while(current != null)
{
current.displayNode();
current = current.next;
}
System.out.println(" ");
}
}
Linked Stack Class
public class LinkedListStack
{
private LinkedList node;
public LinkedListStack()
{
node = new LinkedList();
}
public boolean isEmpty()
{
return node.first == null;
}
public void push(String data)
{
node.insertFirst(data);
}
public String pop()
{
return node.deleteFirst();
}
public void displayStack()
{
System.out.println("Reversed order: ");
node.displayNode();
}
}
My main method (this is where i am getting very stuck)
import java.util.Scanner;
import java.util.Stack;
public class LinkedStackDemo
{
public static void main(String []args)
{
LinkedListStack s = new LinkedListStack();
LinkedList s1 = new LinkedList();
String input;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a word: ");
input = scan.nextLine();
s.push(input);
//String reverse = new StringBuffer(s.push(input)).reverse().toString();
//System.out.println(reverse);
for (int i = 1; i <= input.length(); i++)
{
while(i<=input.length())
{
String c = input.substring(i,i-1);
s.push(c);
}
//System.out.println("The stack is:\n"+ s);
s.displayStack();
}
}
}
I fixed the most recent problem but now it prints the code vertically instead of horizontally, this was my most recent problem.
This how it prints it out, the desired output would be to print the reverse like this, " olleH "Please enter a word: Hello Reversed order: H Hello Reversed order: e H Hello Reversed order: l e H Hello Reversed order: l l e H Hello Reversed order: o l l e H Hello
Taking out the System.out.println(" "); from displayNode; did not fix the problem for it printing out vertically.
The vast majority of the code here is totally irrelevant to the problem you describe. The only relevant bit is this:
for (int i = 1; i <= input.length(); i++)
{
while(i<=input.length())
{
String c = input.substring(i,i-1);
s.push(c);
}
//System.out.println("The stack is:\n"+ s);
s.displayStack();
}
The actual problem that you're seeing is the exception caused by passing in i and i-1 to String.substring. As it says in the Javadoc (emphasis mine):
[Throws] IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
So, you need to call something else, like input.substring(i-1, i).
But there's another problem here: your while loop will never terminate, because i and input never change, so i<=input.length() never changes. As such, you'd just keep on pushing c into the stack until you run out of memory.
This while loop is simply unnecessary; remove it.

Issue passing argument to my main using DFS - Java

I am trying to get this code running as fast as possible when traversing through my stack of my DFS currently the input files are like so:
0 2
2 1
1 4
4 5
5 6
10 8
8 9
9 6
7 6
3 4
0 1
3 9
0 4
Where my Maze class will tie the numbers together and create a graph for me. After the graph is created my DFS class runs through traversing giving one or all solutions to the .txt file submitted.I have recently altered my Maze class as for it to run more efficiently but am being thrown errors and the data is parsing through to my DFS to be outputted. My Maze class is as follows:
import java.io.*;
import java.util.*;
public class Maze {
private final Map<Integer, Set<Integer>> adjList = new HashMap<>();
/**
* The main constructor that takes a String for reading maze file.
*
* #param file
*/
public Maze(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
while (scan.hasNextInt()) {
int node1 = scan.nextInt();
int node2 = scan.nextInt();
this.connect(node1, node2);
this.connect(node2, node1);
}
}
}
/**
* Makes a unidirectional connection from node1 to node2.
*/
private void connect(int node1, int node2) {
if (!this.adjList.containsKey(node1)) {
this.adjList.put(node1, new HashSet<Integer>());
}
this.adjList.get(node1).add(node2);
}
/**
* Returns a human-readable description of the adjacency lists.
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Map.Entry<Integer, Set<Integer>> adj : this.adjList.entrySet()) {
int from = adj.getKey();
Set<Integer> to = adj.getValue();
s.append(from).append(" connected to ").append(to).append('\n');
}
return s.toString();
}
/**
* Returns the set of nodes connected to a particular node.
*
* #param node - the node whose neighbors should be fetched
*/
public Iterable<Integer> getadjList(int node) {
return Collections.unmodifiableSet(adjList.get(node));
}
/**
* Demonstration of file reading.
*/
public static void main(String[] args) throws FileNotFoundException {
System.err.print("Enter File: ");
Scanner scanFile = new Scanner(System.in);
String file = scanFile.nextLine();
Maze m = new Maze(new File(file));
System.out.println(m);
}
}
And my DFS looks like so.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
public class DFS {
//starting node, the route to the next node, has node been visited
private int startNode;
private int[] route;
private boolean[] visited;
// 2 main arguments - Maze File & user input
public DFS(Maze maze, int inputInt) {
int startNode = 0;
int goalNode = 1;
route = new int[maze.node];
visited = new boolean[maze.node];
//Takes user's input and runs desired function
if(inputInt == 1){
findOne(maze, startNode, goalNode);
}
else if (inputInt == 2){
findAll(maze, startNode, goalNode);
}
else {
System.out.println("input invalid. No Solution Returned");
}
}
//Put path to goal in the stack
public Stack<Integer> route(int toGoalNode) {
if (!visited[toGoalNode]) {
return null;
}
Stack<Integer> pathStack = new Stack<Integer>();
for (int routeGoalNode = toGoalNode; routeGoalNode != startNode; routeGoalNode = route[routeGoalNode]) {
pathStack.push(routeGoalNode);
}
pathStack.push(startNode);
reverseStack(pathStack);
return pathStack;
}
//Reverse the stack
public void reverseStack(Stack<Integer> stackToBeReverse) {
if (stackToBeReverse.isEmpty()) {
return;
}
int bottom = popBottomStack(stackToBeReverse);
reverseStack(stackToBeReverse);
stackToBeReverse.push(bottom);
}
//Pop the bottom of the stack
private int popBottomStack(Stack<Integer> stackToBeReverse) {
int popTopStack = stackToBeReverse.pop();
if (stackToBeReverse.isEmpty()) {
return popTopStack;
} else {
int bottomStack = popBottomStack(stackToBeReverse);
stackToBeReverse.push(popTopStack);
return bottomStack;
}
}
//performs DFS and unsets visited to give the result of all paths
private void findAll(Maze maze, int node, int goal) {
visited[node] = true;
if(node == goal) {
printPath(goal);
} else {
for (int con : maze.getadjList(node)) {
if (!visited[con]) {
route[con] = node;
findAll(maze, con, goal);
}
}
}
visited[node] = false;
}
//performs DFS and maintains visited marker giving only one path
private void findOne(Maze maze, int node, int goal) {
visited[node] = true;
for (int con : maze.getadjList(node)) {
if (!visited[con]) {
route[con] = node;
findOne(maze, con, goal);
}
}
}
//Traverse the connections to the goal and print the path taken
public void printPath( int toGoal) {
int goalNode = 1;
if (visited[toGoal]) {
System.out.println("Completed Path: ");
for (int t : route(toGoal)) {
if (t == toGoal) {
System.out.print(t);
} else {
System.out.print(t + " -> ");
}
}
System.out.println();
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanFile = new Scanner(System.in);
int goalNode = 1;
System.out.print("Enter maze file: ");
String file = scanFile.nextLine();
Maze maze = new Maze(new File(file));
Scanner scanInt = new Scanner(System.in);
System.out.print("Enter desired feedback (1 = one soultion, 2 = all): ");
int inputInt = scanInt.nextInt();
// maze.toString();
System.out.println(maze);
DFS dfs = new DFS(maze, inputInt);
dfs.printPath(goalNode);
}
}
I've been looking over it for a while and can't figure out exactly why the data is parsing and being used. Ive altered a few things here and there but have been thrown even more errors. They specifically say
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at DFS.findOne(DFS.java:90)
at DFS.<init>(DFS.java:22)
at DFS.main(DFS.java:127)
Referencing to the lines of code:
visited[node] = true;
findOne(maze, startNode, goalNode);
DFS dfs = new DFS(maze, inputInt);
Now essentially im lead to believe that there is no argument being passed, if someone could pin point the problem and lend a hand in helping me out it would be greatly appreciated. Thanks again
EDIT:: Old version of Maze class
import java.io.*;
import java.util.*;
public class Maze {
static Set<Integer> Nodes = new HashSet<Integer>();
List<Integer>[] conList;
int node; //declaring value for my nodes.
int con; // declaring a connection
//Constructor takes an int parameter to read through the list of corresponding nodes
Maze(int node) {
this.node = node;
this.con = 0;
conList = (List<Integer>[]) new List[node];
for (int index = 0; index < node; index++) {
conList[index] = new LinkedList<Integer>();
}
}
//Constructor that takes a String of the maze file
public Maze(String mazeFile) {
this(nodeSize(mazeFile));
Scanner scan;
try {
//Creates a scanner for reading the file and loops through linking the nodes to their connections.
scan = new Scanner(new File(mazeFile));
while (scan.hasNextInt()) {
int firstNode = scan.nextInt();
int secondNode = scan.nextInt();
addCon(firstNode, secondNode);
}
} catch (FileNotFoundException ex) {
System.out.println("File Not Found.");
}
}
/*Takes String parameter which is the name of the maze file.
* Method designed to return the the size of the set of nodes
*/
public static int nodeSize(String mazeFile) {
Scanner scanNodeSize;
try {
scanNodeSize = new Scanner(new File(mazeFile));
//while scan has more int's left repeat.
while (scanNodeSize.hasNextInt()) {
int firstNode = scanNodeSize.nextInt();
int secondNode = scanNodeSize.nextInt();
Nodes.add(firstNode);
Nodes.add(secondNode);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return Nodes.size();
}
//Method designed to connect the first and second nodes
private void addCon(int firstNode, int secondNode) {
con++;
conList[firstNode].add(secondNode);
conList[secondNode].add(firstNode);
}
//outputs the nodes and their connection's (#remove later?)
public void print() {
for (int n = 0; n < node; n++) {
System.out.print(n + " connected to ");
for (int w : conList[n]) {
System.out.print(w + " ");
}
System.out.println();
}
}
//method returns a list, enabling nodes to be easily accessible.
public Iterable<Integer> getconList(int nodes) {
return conList[nodes];
}
}
You are getting an index out of bounds exception at 0. This should lead you to believe that the array has not properly been initialized. You initialize the visited[] array with maze.node however nowhere in your code do we see where this node variable is located. You need to give a proper value to maze.node if you want this to even be runnable.
*EDIT - My above answer is no longer applicable now that we have your previous Maze class which explains why the code will not run.
There are so many things wrong with the code in its current state so I will try and give you some direction here:
Your new way of creating a Maze is to read from the file and connect the 2 points and store them in an Map. The issue with this is that you cannot just get the next element since you have to have the key to get the element. To fix this you should use a different data structure.
public DFS(Maze maze, int inputInt) {
int startNode = 0;
int goalNode = 1;
route = new int[maze.node]; //!!! maze.node isn't a thing anymore
visited = new boolean[maze.node]; //!!! maze.node isn't a thing anymore
You can see that you are trying to access maze.node which use to be a variable of Maze. It no longer is. You need to find a new way of getting a node from Maze. To do this you need to grab the node from your data structure in a different way:
public DFS(Maze maze, int inputInt) {
int startNode = 0;
int goalNode = 1;
route = new int[maze.adjList.getNode()];
visited = new boolean[maze.adjList.getNode()];
You have a lot of options for a different data structure for you adjacency list but something such as this:
http://theoryofprogramming.com/adjacency-list-in-java/
will give you a decent starting point.

Java: Why is my array of objects overwriting all the previous data inside a loop?

I try to make an array of nodes with a node on a specific place in the array.
For example:
I add a node in the array and set its number to 1.
I add another node in the array on the next position and set its number to 2.
Both nodes got the number 2 now.
Sample of the code:
public static String run(InputStream in) {
Scanner sc = new Scanner(in);
//indicating values
sc.nextInt(); /* int vertices = */
int edge = sc.nextInt();
int start = sc.nextInt();
int end = sc.nextInt();
if (start == end) {
sc.close();
Path = "yes";
} else {
nodes = new Node[edge + 1];
for (int i = 1; i < edge; i++) {
//Node values
int number = sc.nextInt();
int next = sc.nextInt();
sc.nextInt(); /* int distance = */
Node node = new Node(number, next);
if (nodes[number] == null) {
nodes[number] = (node);
} else {
nodes[number].addChild(next);
}
}
hasPath(nodes[start], end);
}
sc.close();
return Path;
}
Sample of the Node code:
import java.util.ArrayList;
public class Node {
private ArrayList<Integer> childs = new ArrayList<Integer>();
private static int number;
public Node(int n, int next){
number = n;
childs.add(next);
}
public int getNumber(){
return number;
}
public void addChild(int child){
childs.add(child);
}
Can anyone please help me?
The problem is with declaring the number member static. This means there's only one such member for the Node class, instead of each instance having its own member. Just define it as an instance variable, and you should be fine:
public class Node {
private ArrayList<Integer> childs = new ArrayList<Integer>();
private int number; // Note the static was removed
// rest of the class

how can implementing a heap that each node is a class?

I want to crate a Heap structure that each node have 2 data , 1) string 2) int
so i think that each node must be a Class that's name is "heapNode" , but i have a trouble in swap method ,
please help me
import java.util.ArrayList;
public class MainHeap {
ArrayList<heapNode> heap;
MainHeap (){
new ArrayList<heapNode>();
}
public int getMin(){
return heap.get(0).data ;
}
private int parent(int pos) {
return pos / 2;
}
private void swap(int pos1, int pos2) {
heapNode temp =new heapNode();
temp = heap.get(pos1);
heap.get(pos1) = heap.get(pos2);
heap.get(pos2) = temp;
}
public void insert(int elem) {
int max = heap.size();
heap.get(max).data = elem ;
int current = heap.size() ;
while (heap.get(current).data < heap.get(parent(current)).data){
swap ( current , parent(current));
}
}
}
and this is my heapNode class
public class heapNode {
int data;
String fileName;
}
the swap method has error but i cant solve errors
Your swap code actually makes the objects point to different objects. It does not modify the positions in the arraylist itself. If using arraylist, you will have to remove an object from an index and set that object at a new index to swap or else you can use other data structure.
java.util.PriorityQueue<YourClass>

Categories

Resources