Stack and Queue java [closed] - java

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 2 years ago.
Improve this question
I have to create a program that follow this instructions. create a Java stack consisting of four (4) book titles entered by the user. Pop the stack's elements one by one; each popped element will be added to a queue. Then, print the content of the queue.
and here is the code I have come up but yet didn't got the desired output.
import java.util.Scanner;
import java.util.Queue;
import java.util.Stack;
import java.util.LinkedList;
public class books {
public static void main(String[] args) {
Queue book = new LinkedList < String > ();
Stack < String > Title = new Stack < > ();
Scanner user = new Scanner(System.in);
System.out.println("Enter four book titles.");
int b = 4;
for (int i = 1; i <= b; i++) {
System.out.print("Book " + i + ":");
String Enter = user.nextLine();
Title.push(Enter);
Title.pop();
book.offer(Title);
}
System.out.println("New order of books:");
System.out.println(book);
}
}
The output is something like this
Enter four book titles.
Book 1:b1
Book 2:b2
Book 3:b3
Book 4:b4
New order of books:
[b1, b2, b3, b4]

What you were doing was every time enque the whole Title stack to the queue because pop method returns the fist element to be removed from the stack
Also ....
You have to first put ALL elements in the stack and then create one more loop to add them to the queue because this way you add the first element to the stack also as first element in the queue
After int b=4 this should be your code:
for(int i=1; i<=b;i++){
System.out.print("Book " + i + ":");
String Enter = user.nextLine();
Title.push(Enter);
}
for(int i=1;i<=b;i++){
book.offer(Title.pop);
}
instead off offer (which returns booolean) you could also use add() which throws exception if the capacity of the container is full , but your programm here is really simple so there is no way this will happen

Related

how to Remove object from list based on certain condition (java)? [closed]

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 2 years ago.
Improve this question
am trying to find a way to remove an object from a list based on a condition, the object is a patient that have an age attribute, i want to remove every patient that is older than 25 age from a list, the code consist of 4 lists that is categorized based on certain info any way here is my code:
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
Scanner kb = new Scanner(System.in);
boolean flag = true;
System.out.print("Enter number of patients: ");
int n = in.nextInt();
AList patients = new AList(n); //All Patients
AList Apatients = new AList(); //category "A" Patients
AList Bpatients = new AList(); //category "B" Patients
AList Cpatients = new AList(); //category "C" Patients
//Add Patients to the list:
for(int i =0; i < n ; i++){
Patients p = new Patients();
System.out.print("Enter Patient name: ");
p.name = kb.nextLine();
System.out.print("Enter Patient ID: ");
p.id = in.nextInt();
System.out.print("Enter Patient Age: ");
p.age = in.nextInt();
flag = true;
while(flag){
System.out.print("Enter Patient Category: ");
p.category = kb.nextLine();
System.out.println("\n\n");
if(p.category.equals("a") || p.category.equals("A")){
Apatients.add(p);
flag = false;
}
else if(p.category.equals("b") || p.category.equals("B")){
Bpatients.add(p);
flag = false;
}
else if(p.category.equals("c") || p.category.equals("C")){
Cpatients.add(p);
flag = false;
}
else{
System.out.println("Wrong Entry...! Try Again");
}
}
patients.add(p);
}
//Display all patients:
System.out.println("All Patients information : ");
patients.display();
System.out.println("Category A Patients : ");
Apatients.display();
System.out.println("Category B Patients : ");
Bpatients.display();
System.out.println("Category C Patients : ");
Cpatients.display();
//From the list for A category remove each patient with age > 25 year:
for(int i=0; i < Apatients.getLength();){
// here is my problem how to iterate the list and check for any patient age > 25 to remove it?
}
}
You have many, many bugs in this code.
2 scanners
You should have only one Scanner object. Why do you have both kb and in? Delete one.
mixing nextLine and nextAnythingElse
You can't mix those. The usual thing to do is to never use nextLine(); to read a line of text, just use next(). This does require that you update the scanner's delimiter; immediately after making the scanner object, call in.useDelimiter("\r?\n"); on it.
AList isn't a thing
Whatever might 'AList' be? It's not in core java and it doesn't sound like it is required here; just use ArrayList<Patient> instead
naming a class with a plural name.
Clearly a single Patients instance represents a single patient, therefore, you should call it Patient, because what you have is clearly confusing you.
You're breaking with convention.
thisIsAVariableName, ThisIsATypeName, THIS_IS_A_CONSTANT. That should be aPatients, not APatients. This makes your code hard to read, and given that you're using a community resource (Stack Overflow), that's not good.
Your actual question
Given that AList is not a thing and you didn't paste it, it is not possible for anybody on SO to answer this question. Update the question and include the API of AList, or stop using it (there is no reason to use this, unless it is mandated because this is homework, in which case, you should ask your teacher for help on this; they get paid, and are the ones who are supposed to support this AList class you're using). Had you been using ArrayList, there are a number of ways to do this. But first a concern: If you loop through each item by way of 'index', then removing an element shifts all indexes down by one, which makes the math complicated. One extremely easy way out of that dilemma is to loop through the list backwards to forwards, because then the shifting of indices doesn't have an impact.
Option #1: Iterators
var it = aPatients.iterator();
while (it.hasNext()) {
Patient p = it.next();
if (p.getAge() > 25) it.remove();
}
Option #2: Backwards loop
for (int i = aPatients.size() - 1; i >= 0; i--) {
if (aPatients.get(i).getAge() > 25) aPatients.remove(i);
}
Option #3: removeIf
aPatients.removeIf(pat -> pat.getAge() > 25);

Obtain the largest number in an array of numbers [closed]

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
This is my first time doing java and I am am trying to get the largest number from an array of x numbers using a method called bigNum(). Can anyone tell me why this doesn't work?
class project3
{
public static void main(String args[])
{
int total =0;
int b;
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for (int i=0; i < maxItems; i++)
{
b = EasyIn.getInt();
}
bigNum(b);
}
public static void bigNum(int maxItems)
{
for (int i = 1; i >= maxItems; i++)
{
if (bigNum(b) >= maxItems)
bigNum(b) = maxItems;
}
return bigNum(b);
}
}
You're probably getting compiler errors at this point due to unmatched braces. You want your program to have matched braces, and you also want to avoid having methods inside of other methods.
You want to have something that has the following form
class project3
{
public static void main(String args[])
{
...
}
public static int bigNum(int maxItems[])
{
...
return someInt;
}
}
// capital letter for the class (convention)
public class Project3 {
public static void main(String args[]) {
//int total = 0; // you never used this number
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for(int i = 0; i < maxItems; ++i) {
int newNumber = EasyIn.getInt();
/* you want to put the numbers into an array,
so don't call "bigNum" but put them there: */
numbers[i] = newNumber;
}
// now find the big number:
int bigNumber = bigNum(numbers);
System.out.println("The biggest number: " + bigNumber);
}
// first: change the return type to get the biggest number
// second: pass the reference to the array, not a single number
// public static void bigNum(int maxItems) {
public static int bigNum(int[] items) {
// create big number, assume it's very small:
int bigNumber = Integer.MIN_VALUE;
// this for loop will never run, change it a bit:
//for(int i = 1; i >= maxItems; i++) {
for(int i = 0; i < items.length; i++) {
// your idea is correct, but you can not use the
// method here, see explanations below
// Also don't check for the number of Items, but for
if(items[i] > bigNumber) {
bigNumber = items[i];
}
}
return bigNumber;
}
}
Explanations and further readings
Class name: Java has lots of different naming conventions, but the most common rules are: ClassNames/Types in CamelCase with a Capital at the beginning, variableNames following a similar convention but with a leading small letter. This makes it much easier to read code.
Indentation: Try to use a more consistent indentation. Also supports readability. Actually some other programming languages even rely on correct indentation.
Try to understand what variables and what methods are and how to use them (and return from them, you can not assign values to a method in Java. While you read the latter tutorial focus on return types and how to call methods correctly, you can not return an int when your method is of type void. Also the parameters need to be exactly defined.
Apart from that try to compile your code before you post it. As your code went, it should have thrown lots of compile errors, e.g. bigNum(b) = maxItems; should tell you that the left-hand side of an assignment needs to be a variable. This can help you a lot while tracking down mistakes.
Another error is that for most people EasyIn will not be defined (as it is for me, so the code I posted above might actually not be working, I didn't try). I suppose it's a learning library (we had our AlgoTools back in our first Java lectures). Still it would be nice to tell us what it is and what other imports you use (common mistake when I let my IDE decide my imports for me: java.util.Date and java.sql.Date).
Also try to make clear to yourself what you want to achieve with your program and how. Your algorithm actually looks like you didn't think too much about it: You try to find a biggest number and always check "a big number" against the number of expected items, which then might become "the big number" as well. Or something like that.
Programming is being concise and exact, so make a plan before. If it's too hard for you to think about a solution directly, you can maybe draw it on paper.
And if you then have problems, after compiling, asking your program, asking google, asking stack overflow: provide us with as many details as you can and we will be able to help you without just posting some code.
Good luck!

Calculator in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Lately I've worked on simple calculator that can add, substract, multiply and divide.
public static void main(String arr[]){
double num1, num2;
String ans = null;
System.out.println("Calculator manu:");
System.out.println("\n"+"a for adding");
System.out.println("b for substracting");
System.out.println("c for multiplying");
System.out.println("d for dividing");
Scanner NumInput = new Scanner(System.in);
System.out.println("\n"+"Enter number one: ");
num1 = NumInput.nextDouble();
System.out.println("\n"+"Enter number two: ");
num2 = NumInput.nextDouble();
while(true)
{
Scanner AnsInput = new Scanner(System.in);
System.out.println("\n"+"Choose operation.");
String answer = AnsInput.next();
if(AnsInput.equals("1"))
{
answer = Double.toString(num1+num2);
System.out.println("\n"+"The sum of the first and second number is: "+answer);
}
else if(AnsInput.equals("2"))
{
answer = Double.toString(num1-num2);
System.out.println("\n"+"Subtraction of the first and the second number is: "+answer);
}
else if(AnsInput.equals("3"))
{
answer = Double.toString(num1*num2);
System.out.println("\n"+"The product of the first and second number is: "+answer);
}
else if(AnsInput.equals("4"))
{
answer = Double.toString(num1/num2);
System.out.println("\n"+"Ratio of the first and the second number is: "+answer);
}
}
}
But what if I want to wright program that works like an ordinary calculator; it adds, subtracts, multiplies, divides, ... ,but not only whit two but multiple numbers.
This can certainly be done! Although it requires substantial framework. However, if you want to use this type of simplistic code, what you need to do is store the numbers somewhere else, outside this function, and every two numbers you apply an operation to, you store it and use it as the first argument along the third you wanted to use. And so on. Does this make sense?

Cannot resolve nullpointerexception [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
System.out.println("Welcome to the Personal Contact Assistant!");
System.out.println("How can I help you?");
System.out.println("(add) (get) (quit)");
String option = input.nextLine();
Contact[] Contacts;
Contacts = new Contact[500];
int index = 0;
boolean finished = false;
while(finished==false){
switch (option) {
case "add":
System.out.println("You have selected add.");
Contact newContact = new Contact();//constructs new contact object called newContact
newContact.setNewInfo();//gathers input for newContact
System.out.println("Contact Will be Saved as:");
newContact.print();//prints gathered information
Contacts[index] = newContact;//saves contact to array
index++;//advances index
System.out.println("Can I do something else for you? (add) (get) (quit)");
option = input.nextLine();
break;
case "get":
System.out.println("You have selected get.");
System.out.println("Enter the contact's first name:");
String tempName;
tempName = input.nextLine();
for(int i=0; i<499; i++){
System.out.println(":"+i);
if(Contacts[i].getFirstName().equals(tempName)){
System.out.println("Contact Found:");
Contacts[i].print();}
}
System.out.println("Can I do something else for you? (add) (get) (quit)");
option = input.nextLine();
break;
These are add and get segments for a contact app I am working on. My Contact class contains methods for setting and getting name, address etc of contacts. I receive no compiler errors but while running the program I get a nullpointerexception error at the for loop. additionally the output will only print 1 number from the System.out.println(":"+i); line (which I added to find out how many loop iterations were actually happening), unless it finds a contact with that first name, in which case it returns the full contact information for each contact and then errors out. I just want it to complete the loop, print ever contact with that first name, and then go back to the main outer loop. Help?
If you run get() before manually adding 500 contacts, ghis line will throw when i exceeds the number of contacts you've added, since we go to 499 regardless of the number you have added.
if(Contacts[i].getFirstName().equals(tempName)){
Even if it finds the one you're looking for, it will continue on through 499. There are a few ways to fix it.
If it's expected that you'll always find it, stop when you find it.
Change the loop to:
for (i = 0; i < index; i++)
Use an ArrayList or other collection class, which manages size for you. Then your search can become:
for (Contact contact : Contacts) {

Java 1.4.2 - ArrayIndexOutOfBounds Error [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
(I am using Java 1.4.2) I wanted to have an array that should flip a 'coin' a certain amount of times given by the user (the coin can flip up to 1000 times). Then randomly generate an integer between 1 and ten, store all the numbers in an array. I have the following code but it keeps on giving me the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at CoinFlip.main(CoinFlip.java:42)
Here is the code I wrote.
import java.io.*;
import java.math.*;
public class CoinFlip
{
public static void main(String[] args) throws IOException
{
// setting up variables
String timesString;
int times;
// setting up input
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
do
{
// times will display how many times the coin will flip
// loop if times does not fulfill the requirements
System.out.println("How many times do you want the coin to flip? (MUST be an integer between 1 to 1000)");
timesString = in.readLine();
// convert timesString into an integer
times = Integer.valueOf(timesString).intValue();
if((times > 1000)||(times < 1))
{
System.out.println("ERROR: The number of times you flip the coin must be an integer between 1 and 1000.");
}
System.out.println("The value for times is " +times);
}
while((times > 1000)||(times < 1));
// create a new array
double flip[] = new double[times];
// create a new variable timeStore that sets the boolean conditions for the For Loop
int timeStore;
for(timeStore = 0; timeStore <= times-1; timeStore++)
{
System.out.println("timeStore (how many iterations) is " +timeStore);
System.out.println("FOR LOOP: When " +timeStore+ " is less than or equal to " +(times-1));
flip[times] = Math.round(Math.random()*9)+1;
// the line above stores a random integer between 1 and 10 within the current index
System.out.println("flip["+times+"] = "+flip[times]);
}
}
}
At line 42;
flip[times] = Math.round(Math.random()*9)+1;
Should be;
flip[timeStore] = Math.round(Math.random()*9)+1;
Then also in the System.out on line 44.
These are wrong:
42: flip[times] = Math.round(Math. random()* 9 ) + 1;
44: System.out.println("flip[" + times + "] = " + flip[times]);
It appears you meant
42: flip[timeStore] = Math.round(Math.random()*9)+1;
44: System.out.println("flip["+timeStore+"] = "+flip[timeStore]);
Since you declared flip as an array of size times, only indices 0...(times - 1) are valid. In particular, index times is invalid and so flip[times] will throw.
Note that the compiler was telling you the offending line, and the offending index passed in. It's telling you you passed in 7 as the index. But note, this exception is happening on the first iteration of your loop. You can tell this by the output that your program would have produced since you have helpful print debugging statements in your code. Thus, you should have been able to reason: hey, why is my array seeing the index 7 on the first iteration of the loop when the index should be 0? At that point, the error practically figures itself out.
Also, idiomatic usage of arrays is:
for(timeStore = 0; timeStore < times; timeStore++)
but even better is:
for(timeStore = 0; timeStore < flip.length; timeStore++)

Categories

Resources