Practicing Java, need help finding the output - java

I am looking to find the output of the following code.
Suppose that myStack is a linked implementation of a stack of Integers.
What would the output be for this code?
myStack.push(new Integer(1));
myStack.push(new Integer(2));
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());

If this is the only code, then I believe it should throw a run time exception because you try to pop an element out of a stack when the stack size is zero.
So your output would be something like:
2
1
Error!!!!
Though that third line really depends on how your pop() method handles a stack with zero size.

Related

How can I read a file and store its objects into my custom linked list?

Basically, I am not using any of the Java API classes such as ArrayLists or LinkedLists, as I have created my own custom linked list class which in this case is named FoodList. I am trying to figure out a way to read each line from a file where each line is an object, and store it in FoodList.
I've looked at many examples of reading files online, but none of them were for a custom linked list.
package lab9;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Console {
FoodList x = new FoodList();
public Console(){
this.x = new FoodList();
}
public void Display() {
System.out.println("============================================================================");
System.out.println("Name Food Group Calories Daily percentage ");
System.out.println("============================================================================");
File f = new File("food.txt");
try {
Scanner scan = new Scanner(f); //What I tried to do to read in objects from file
while(scan.hasNextLine()){
String line = scan.nextLine();
String[] details = new String[4];
details = line.split(" ");
String name = details[0];
String group = details[1];
int calories = Integer.parseInt(details[2]);
double percentage = Double.parseDouble(details[3]);
x.add(new Food(name, group, calories, percentage));
}
System.out.println(x);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Not working");
}
}
}
The code below is also giving me an out of bounds exception at line 30. Should I try to read the objects differently or fix this?
NOTE: PLEASE do not mark this as a duplicate, I have already made my String[] details variable to hold more than 1 array.
This was originally closed as a dup of What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
This answered at least part of the problem. You were getting that exception, and the dup does explain what causes the exception, though it doesn't address the specifics of your particular code.
(Aside: there are a lot of people, including me, who believe that questions like this where the OP expects someone else to debug their code are best answered by pointing the OP at somewhere with the information they need to find the solution for themselves. Directly solving the problem for the OP deprives the OP of the learning exercise of finding the solution themselves, and leads to people getting qualifications without actually knowing how to solve programming problems for themselves.)
Then you say this:
NOTE: PLEASE do not mark this as a duplicate, I have already made my String[] details variable to hold more than 1 array.
(It is a duplicate ... according to that is normally meant here by duplicate!)
That is the wrong fix. 1) It means that you didn't use the clues provided to understand what the problem really was. 2) It also implies a significant misconception about what happens when you assign an array.
Circling back, here is the logic process for diagnosing and fixing the problem:
Q: What has happened?
A: Got an exception.
Q: What does the exception mean?
A: Read javadocs, google it.
Q: Where did you get the exception?
A: You can get that from the stack trace (line number) and looking at the code.
Q: Why did you get the exception?
A: There will be clues in the exception message and the line what the exception was thrown. In this case it would say that you attempted to access element zero of an array whose length is zero. I am assuming that you haven't added / removed lines and line 30 is this one:
String name = details[0];
Clearly you cannot access the zero'th element of an empty array. (Why? review your notes on arrays and how they are indexed!)
That gives you two things to look at:
Why was the array's length zero?
Why were you trying to access that element of a zero length (empty) array?
The first can be answered by reading through the javadoc for String::split, and thinking about it. The line you were trying to split must have been empty. (If there were any non-blank characters in it, the length of the array would have been > zero and you wouldn't have gotten an exception on line 30.)
If you look carefully at the input file you should be able to spot the empty line. (It could be at the end of the file.) And my guess is your problem's requirements mention the empty line. (They should.)
The second is simple. You didn't consider the possibility of an empty line in the input, and that would give you an empty array. Your code assumes that the array is non-empty.
Q: How do you fix it?
A: You need to know what you want to happen in each of those scenarios. Then you write code to implement that. Here are a couple of strategies:
Trim each line (to remove extraneous leading / trailing whitespace) and test if the resulting string has length zero. If it is, skip the line.
Split the line, and check how many elements there are in the array. If the number is NOT 4, do something appropriate. (Skip the line, report an error, whatever. You decide.)
Then test it.
Earlier I said this:
That is the wrong fix. ... 2) It also implies a significant misconception about what happens when you assign an array.
String line = scan.nextLine();
String[] details = new String[4]; // <<-- supposed fix
details = line.split(" ");
Array assignment is actually a reference assignment. So the line after your fix is going to replace the 4 element array that you created with a new array created by the split call. The array may well have a different length. It will definitely be a different array.
In short, that fix actually doesn't have any effect.

How can you properly make a Stack with Integers on BlueJ?

I've been using BlueJ for a while now and recently, we've started making and working on Stacks and Arrays in my class. This is basically what I have to do currently:
Create the class "StackTest", which contains a Stack called "zahlen" with values of the type "Integer". Add the numbers 5, 10, 50 and 30 to the Stack respectively. Finally, run the Stack and it should show all values that are bigger than 10 in the console.
They also gave us certain keywords that have to be used at least once in the class: Keywords
import java.util.Stack;
public class StackTest
{
public StackTest(){
Stack zahlen = new Stack();
zahlen.push(5);
zahlen.push(10);
zahlen.push(50);
zahlen.push(30);
while (!zahlen.isEmpty()){
if(zahlen.top()>10){
}
zahlen.pop();
}
}
}
My problem is that first of all, I don't know what exactly the Integer in parenthesis is or what it can be used for (talking about (Integer) ) and I also don't know how you can check if the top number ( zahlen.top() ) can be used in the if command.
I think it would be genuinely worth your while to read up on the Stack class in the official Java documentation:
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
It can be a bit dense, but it contains a lot of useful information. This will give you the info you need regardless of using BlueJ, Eclipse, or any other IDE. :-)
A stack follows LIFO rule (Last-In-First-Out). Think of a stack like a stack of dirty plates that you want to clean, to clean a plate you would take a plate on top of the stack rather than reach for the bottom or the middle. In your case rather than a stack of dirty plates, it's a stack of Integers.
Once you've created your stack collection, you push() elements into the stack in your code example it would look something like this:
|30|
|50|
|10|
|5 |
¯¯
Note that you don't have access to any of elements aside from the top of stack (30 in this case). To gain access to elements below you have to pop() the stack which will remove it from the collection.
For example:
int value = zahlen.pop();
will cause value to be equal to 30 and your new stack collection will look like this:
| |
|50|
|10|
|5 |
¯¯
You can now use value to check whether or not it's greater than 10 then use
System.out.println() to print out the value to the console, simply loop this till your stack is empty. If you wish to look at the value on top of the stack without popping it off you can use peek() method.

Format java string to look a specific way

I am new to Java and I have 4 int stacks that I need to print out in a specific way. The IDE I am using is BlueJ.
I want to print the arrays to look like the following
|110| |231| |333| |444|
|111| |232| |334| |447|
|112| |233| |335| |448|
|113| |234| |336| |449|
|114| |235| |337| |450|
|115| |236| |338| |451|
I am trying to this with System.out.println("|"+stack1.pop()+"|") but it creates a problem because I am not sure how to go back from the bottom, back to the top. Ex. 115 --> back up to 231. Each column represents a stack.
Thank you!
Use String.format() better than concatenating a bunch of strings
System.out.println(String.format("|%s|\t|%s|\t|%s|\t|%s|",
stack1.pop(),stack2.pop(),stack3.pop(),stack4.pop()));
If you want to print the Stack elements in the opposite order, just reverse the stack first
You wont be able to do that in console:
as an alternative you can print values from each stack and then moving down like:
System.out.println("|"+stack1.pop()+"|\t|"+stack2.pop()+"|\t|"+stack3.pop()+"|\t|"+stack4.pop()+"|" );
Edit
as commented - you can use String.format(...) , check here for formatting options available
How about this :
ArrayList<Stack<Integer>> arrays=new ArrayList<Stack<Integer>>();
arrays.add(stack1);
arrays.add(stack2);
arrays.add(stack3);
arrays.add(stack4);
//Put some code here to Determine the stack size, if all are unequal in size
int size=stack1.size();
for(int i=0;i<size;i++){
String value="";
String temp="";
//4 = if you know the number of stacks is going to be 4 only
for(int j=0;j<4;j++){
//Handle here Empty Stack Exception and print blank
value="|"+(String)(arrays.get(j)).pop().toString()+"|"+" ";
temp=temp+value;
}
System.out.println(temp);
}

How to deal with large arrays in Java [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I am reading a file that has 10,000 int values and then trying to store these in an array. There is an exception thrown which says that the array value is too large.
I was wondering, rather than write this array out in to a variable, could i possibly just keep it in memory and read it from there. Would this be a suitable way of solving this problem?
edit:
After more examination it appears that the error being thrown is a "code to large for try statement" error. I am reading each array element and appending it to a string, maybe this is what is causing the error?
You could use an ArrayList instead - but an array should be fine with 10,000 values. Can you post more detail? Code, full stack trace etc. Theoretically it should be fine with Integer.MAX_VALUE elements (a LOT more than 10k), but of course you may run out of memory first!
In terms of "just keep it in memory and read it from there", well variables are just kept in memory, so whether you use an array or a list (or any other data structure) you'll always be reading it from memory!
EDIT: Based on your additional explanation then it's not a problem with the array size at all, it's a problem with you generating 10,000 lines of code to put in a single block, which is too many and thus it complains. Alter your code to generate code that uses a loop instead and all should be well, however many elements you have in there (up to Integer.MAX_VALUE of course.)
An array of 10,000 int values is about 40KB.
You could try to reduce the memory used further however I suspect this is not your problem.
Can you give us the actual error message? An array value is only too large if its a long e.g. say you used File.length()/4 to determine the size of the array, in which case you need to cast it to an int
It is strange that you cannot create 10000 elements long array. I believe that your problem is not the array length but the value of particular array element. Anyway if you need bigger arrays use Lists instead. Specifically java.util.LinkedList.
Your problem is that you are writing each array or String assignment out in full, something like this:
array[0] = 0;
array[1] = 1;
array[2] = 2;
// all the way up to 9999!
or this:
String s = "";
s += array[0];
s += array[1];
s += array[2];
// all the way up to 9999!
instead of in a loop. So you generate more code than Java will allow in a method.
This results in a compilation error as you describe:
$ javac Test.java
Test.java:7: code too large for try statement
try {
^
Test.java:4: code too large
public static void main(String[] args) {
^
2 errors
Following from discussion in comments, the code that you say is producing this compiler error does not have an enormous number of lines. Something doesn't make sense - the error you report does not line up with the code you say is causing it. At this late stage I strongly recommend that you post some code, and the error so that others can try to understand what might be causing this.
(Also, your question isn't likely to get much attention because you have accepted an answer. You might want to reconsider that if your question is not in fact answered.)
An array of 10,000 ints isn't very big at all. I can't think why you would have a problem keeping the data in memory (ie assigned to a variable).
I find it odd that 10,000 ints takes up too much memory. It could be that other stuff if eating up your memory. Have you tried increasing the available memory to Java? (i.e.-Xmx512m). If this is not possible, you can always try to use shorts or bytes if the numbers are small enough.
The array will take just as much space as chunk of memory (like c does).
This is a known bug in the JVM. It prohibits you from creating an array of integers with size 10,000 (and also 16,384 on Mac OS X). It has to do with the way in which Java translates the byte code into machine code. Changing the size of the array to 10,001 will solve the problem.

How to avoid the 1024 lines of Java exception stack limit [duplicate]

This question already has answers here:
How to get full stack of StackOverflowError
(5 answers)
Closed 4 months ago.
I ran into a Java StackOverflow error, but the offending recursive call is so deep, that it does not give me the full stack trace. It only dumps out the first 1024 lines of methods of the StackOverflow exception.
How can I get the full stack trace, so that I can know the root cause?
The switch -XX:MaxJavaStackTraceDepth allows larger and smaller stack trace lengths. Set it to -1 for an unlimited length. E.g.:
-XX:MaxJavaStackTraceDepth=-1
You can use -Xss to change the stack size, but it won't help if you have unbounded recursion. It sounds like your stopping condition might not be worked out.
Print the stack manually, the limit put on e.printStackTrace() does not apply when you provide a writer (might need to quote me on that but I've never experienced it being cropped when using this method).
Here is some easy code that I employ to get full traces:
/**
* Produces a Java-like stack trace string.
*
* #param e
* #return
*/
public static String exceptionStack(Throwable e) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
return result.toString();
}

Categories

Resources