Java problems creating a new node - java

• Ask the user to enter a set of 5 numbers.
• For each number entered, add it into the front of the linked list.
• Now, ask the user to enter a search number.
• Using a for loop or while loop, search whether the number exist in one of the Nodes in the linked list.
• If there is a matching node, create a new node with data 88 and insert it right before the matching node. Otherwise, display the message “No such number”.
Hi everyone, I would like you to help me with the java code for the last part.
public static void main(String[] args) {
LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt(); sc.nextLine();
for(int i = 0; i < 4; i++){
list.addFront(num);
}
System.out.print("Enter a number: ");
int search = sc.nextInt(); sc.nextLine();
for(Node j = list.getHead(); j!= null; j=j.getNext()){
if((Integer)j.getData()==search){
list.addNode();
}else{
System.out.println("No such number");
}
}
public static Node addNode(T n);//???
}

I think your code will not even work for the first point. What you do is read a number once and then put the same number 4 times into the linked list.
For adding the node to the list before another node you need the index of the node where you want to put it in front of and then use the add(int index, E element) mehtod of the LinkedList. The index can be found by indexOf(Object o).
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

Re factored your code.Here is a working solution.You don't need to create an additional function for addNode().
There is a predefined function known as add(index,element) when you are using java.util.LinkedList.But i would advice to first create your own linklist instead of using predefined LinkedList class.
This will clear all your doubts.
Here i am assumming you are using java.util.LinkedList.
public static void main(String args[]){
LinkedList<Integer> list = new LinkedList<Integer>();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 4; i++)
{
System.out.println("Enter a number: ");
int num = sc.nextInt(); sc.nextLine();
list.addFirst(num);
}
System.out.print("Initial list:"+list);
System.out.print("Enter a number: ");
int search = sc.nextInt(); sc.nextLine();
Iterator<Integer > itr=list.iterator();
int i=0;
boolean flag=false;
while(itr.hasNext())
{
int data=itr.next();
if(data==search){
list.add(i,88);
flag=true;
break;
}
i++; //index of data
}
if(!flag)
{
System.out.println("No such number");
}
else
{
System.out.println("Number inserted at "+i);
}
System.out.print("final list:"+list);
sc.close();
}
Hope it helps you.

Related

Stack: How to check each integer(in a loop) against another integer?

I have to implement a program using Stack which allows a user to enter a positive integer,n, followed by n integers. Then the program should allow the user to enter another integer, val after which the program should display the last value which is greater than val. From my understanding of the program, I figured out that it should compare each element from the top of the stack to the val. Therefore to compare each element to val, it should iterate through the values in the stack starting from the top. I don't really know how to make this work so would be pleased if I could get any help. Here is my program:
public class MyClass{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
Stack<Integer> NumsInStack= new Stack<Integer>();
int n, num, val;
System.out.println("Please enter n.");
n=sc.nextInt();
for(int i=0; i<n;i++){
num=sc.nextInt();
NumsInStack.push(num);
}
System.out.println("Enter a value.");
val=sc.nextInt();
for(int i=0; i<NumsInStack.size();i++){
if(NumsInStack.peek()>val)
System.out.println("The number greater than "+val+" is "+NumsInStack.peek());
}
}
}
You should never iterate over a stack, it defeats the entire purpose of choosing that data structure. You want to use pop and peek:
while (!NumsInStack.empty()) {
if (NumsInStack.peek() > val) {
System.out.println("woot!");
break;
}
NumsInStack.pop();
}
Since you only want it to print out the last number that is higher, you should also put a break; after the print statement so that it breaks out of the loop when it finds a match. Without the break it would print all of the values that are higher.
Working code:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Integer> NumsInStack = new Stack<Integer>();
int n, num, val;
System.out.println("Please enter n.");
n = sc.nextInt();
for (int i = 0; i < n; i++) {
num = sc.nextInt();
NumsInStack.push(num);
}
System.out.println("Enter a value.");
val = sc.nextInt();
while ( !NumsInStack.empty()){
int stackElement = NumsInStack.pop();
if ( stackElement > val){
System.out.println("Stack Element > value :"+stackElement+":"+val);
break;
}
}
}
}

How to make a functioning to do list in java

I am trying to make a functioning to do list with a limit of 10 elements, however I am having an issue with two major things in the to do list.
The first is that after I first compile and run the program and select to add elements to the list, that functions properly, but if I add two elements and the 'stop' sentinel, when I select the next option to print the to do list, I am presented with a list, showing my two elements and then the stop sentinel along with 7 null values in the list. So the first issue I am having is to get rid of the null values, I attempted using a counter as you can see in my code however that was not proving to be effective.
The next issue that I am having is that I am trying to make it so that you can add to the list, so once you select to add more things to the list, the new options the user writes, rewrites over them in the array and prints out the new values and not along with the old ones. I am assuming that can be done through some sort of recursion method but I am having a hard time figuring it out.
Any help would be greatly appreciated!
Thanks!
import java.util.Scanner;
public class ToDo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 10;
String[] list = new String[MAX];
int choice = 0;
while (choice != 3) {
System.out.println();
System.out.println("Type 1 to add a new thing to your to do list.");
System.out.println("Type 2 to print the to do list.");
System.out.println("Type 3 to exit the program.");
System.out.print("Select an option: ");
choice = input.nextInt();
int count = 0;
if (choice == 1) {
System.out.println("Keep hitting enter after to do's, if you want to stop, type 'stop'.");
for (int i=0;i<MAX;i++) {
list[i] = input.nextLine();
if (list[i].equals("stop")) break;
count++;
}
}
if (choice == 2) {
for (int index = 0;index < list.length; index++) {
System.out.println(list[index]);
}
}
}
}
}
As I have mentioned in the comment, you can use an ArrayList instead of String[] to make your processing much easier.
But if you want to use the array itself, there are 3 minor issues with your code.
In your choice 1 for loop, start the loop from count,
for (int i=count;i<MAX;i++) {
list[i] = input.nextLine();
if (list[i].equals("stop")) break;
count++;
}
In your choice 2 for loop, end the loop before reaching count,
for (int index = 0;index < count; index++) {
System.out.println(list[index]);
}
And move your count initialization outside the while loop.
int count = 0;
But beware, if you decide to implement removing tasks, this could get complicated and using ArrayList would become much simpler.
Instead of using a fixed size array of Strings, use an ArrayList of Strings. Then you can add elements to it as you go.
Make sure to
import java.util.ArrayList;
Declaration syntax is
ArrayList<String> myList = new ArrayList<String>();
Add elements to your list with the add() method:
myList.add(input.nextLine())
You don't need that inner for loop, instead break out of the while loop of input options when you've iterated through it 10 times.
To solve your problem of "stop" being in your list, check that the input is "stop", and stop, before you attempt to add to the list.
It is better to use ArrayList but if you still want to stick to String[] then the following program will work for you:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 10;
String[] list = new String[MAX];
int choice = 0;
while (choice != 3) {
System.out.println();
System.out.println("Type 1 to add a new thing to your to do list.");
System.out.println("Type 2 to print the to do list.");
System.out.println("Type 3 to exit the program.");
System.out.print("Select an option: ");
choice = input.nextInt();
String userEnteredItem;
if (choice == 1) {
System.out.println("Keep hitting enter after to do's, if you want to stop, type 'stop'.");
for (int i=0;i<MAX;i++) {
userEnteredItem = input.nextLine();
if(!userEnteredItem.isEmpty()) {
list[i] = userEnteredItem;
if (userEnteredItem.equals("stop")) {
break;
}
count++;
} else {
i--; // Do not increase index for empty item.
}
}
}
else if (choice == 2) {
for (int index = 0;index < count; index++) {
System.out.println(list[index]);
}
}
else {
input.close();
}
}
}
It keeps track of user items in static int count and it also closes the scanner when you do not need it.

Java: removing a specified number of elements from a queue

I have to write a program that creates a queue of Strings. It asks the user to input a number n for which he will have to enter n number of names in the queue. Then until the queue is empty, the program
displays the name on top of the queue
asks the user a number of names to be deleted.
deletes the number of names specified
display the name(s) deleted
The program should use only the add(), remove(), isEmpty() and element() methods.
Here is what I have come up with so far:
package lesson1;
import java.util.*;
public class MyClass1{
public static void main(String[] args) {
Queue <String> strings= new LinkedList<String>();
Scanner input= new Scanner(System.in);
System.out.println("Please enter the number of names, n.");
int n= input.nextInt();
System.out.println("Please enter " +n+ " names");
for(int i=0;i<n; i++){
strings.add(input.next());
}
System.out.println("\nDisplaying the names:\n");
for(String object: strings){
System.out.println(object);
}
while(!strings.isEmpty()){
System.out.println("The name in front of the queue is: " + strings.element());
System.out.println("Please enter the number of names to be deleted:");
int del= input.nextInt();
for(int i=0; i<del; i++){
System.out.println("Name removed:"+strings.remove(i));
}
}
}
}
The problem is that it is printing false for the names being deleted because remove() is a boolean method. How can I fix this?
Both poll and remove returns the deleted object but poll does not throw exceptions if that the problem, no one of them return boolean.
for (int i = 0; i < del; i++) {
System.out.println("Name removed:" + strings.poll());
}

How do I send user inputted integers to a linked list in Java?

I am trying to write code to have users input positive integers and have them sent to a linked list. The users input should end after entering a negative number. Furthermore, I am having issues writing an isSorted boolean method that will return true if the linked list is sorted in increasing order and false otherwise.
Here is the only code I have so far
import java.util.*;
public class List {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
int num = input.nextInt();
}
public boolean isSorted(){
if(){
return true;
}
else{
return false;
}
}
}
public void input() {
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
LinkedList<Integer> ll = new LinkedList<>();
//System.in.available()
Scanner input = new Scanner(System.in);
int num;
while ( input.hasNextInt() ) {
int i = input.nextInt();
if (i >= 0) {
ll.add(i);
}
}
System.out.println(ll+" <-- ll"); //TODO remove debugging code
System.out.println(isSortedAccending(ll)+" <-- isSortedAccending(ll)");//TODO
}
This works by returning false the moment something is found out of order.
public static boolean isSortedAccending(List<Integer> list){
if (list.size() < 2) {
return true;
}
Integer previous = list.get(0);
for (Integer next : list) {
if (previous > next) {
return false;
}
}
return true;
}
Outputs:
Please type positive integers one by one separated by a space.
When you are done, please type a negative integer.
1
2
3
-1
[1, 2, 3] <-- ll
true <-- isSortedAccending(ll)
isSortedDecending() looks exactly the same except it uses <.
import java.util.LinkedList;
import java.util.Scanner;
public class NumberListing {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
int num = input.nextInt();
LinkedList<Integer> list = new LinkedList<Integer>();
while(num > 0){
list.add(num);
num = input.nextInt();
}
if(isSorted(list)){
System.out.println("The list is sorted");
} else{
System.out.println("The list is not sorted");
}
}
public static boolean isSorted(LinkedList<Integer> list){
boolean done = false;
boolean sorted = true;
for(int i = 1; i < list.size() && !done ; i++){
if(list.get(i) < list.get(i-1)){
done = true;
sorted = false;
}
}
return sorted;
}
}
Should be fairly simple. While the number you intake is greater than 0, store the number in a list and get the next one from the console.
After that, loop through the list starting with index 1 to check that each current number is greater than the previous number. I added an early exit so the loop quits anytime a number that is less than the previous number. this means it is unordered and we don't care about the rest.
However, if you're trying to create your own linked list that creates a lot more code and I would suggest looking in a text book or something of the sort to help.
You can put your int's in a container(LinkedList) by using the wrapper class Integer for int. The normal int is a standard primitive type and can not be used by containers, as containers can only work with objects of a class.
LinkedList<Integer> list = new LinkedList();
As for the isSorted method, you could iterate through the list and check if the current value is higher or equal to the previous value.
int prevValue = 0;
for(int i = 0; i < list.size(); i++){
if(!list.get(i) >= prevValue){
return false;
}
prevValue = list.get(i);
}
return true;
You'll want to read the next line as a String, split that line, and walk through the list of elements of that line, adding the positive elements to a LinkedList as you go. Make sure you store your scanner. You'll want to use nextLine, not nextInt.
import java.util.*;
public class List {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
String line = input.nextLine();
String[] integers = line.split(" ");
LinkedList ll = new LinkedList<Integer>();
for (int i = 0; i < integers.length; i++)
{
if (Integer.parseInt(integers[i]) > 0)
ll.add(integers[i]);
}
System.out.println(isSorted(ll));
input.close();
}
Then, just use a simple comparison function for LinkedList to check if it's sorted:
public static <T extends Comparable<T>> boolean isSorted(LinkedList<T> iterable)
{
Iterator<T> iter = iterable.iterator();
if (!iter.hasNext()) {
return true;
}
T t = iter.next();
while (iter.hasNext()) {
T t2 = iter.next();
if (t.compareTo(t2) > 0) {
return false;
}
t = t2;
}
return true;
}

Student Array menu

I'm coding a menu to store names into an array, then giving options to add/delete students and search for a particular student as well, but I cant seem to find out how to set the array so that I can use it in other options, cause, for example, my code only allows me to input names when I use option 1, but it doesnt keep these names in the array when I choose option 3 to search for a name within the array, it just shows up as null for every slot in the array.
Another problem I am having is about how I can delete students, obviously it would be really easy if the name is at the end of the array but what if the name is in the middle, how would I be able to delete the name, shift all the other names down one slot so that there are no gaps in the array?
import java.util.Scanner;
public class Lab10Ex2 {
public static void main(String[] args) {
int choice = 0;
int[] stringArray = {};
do{
String[] stringarray = new String[20];
System.out.println("----------------MENU---------------");
System.out.println();
System.out.println("1. Add Students");
System.out.println("2. Delete Students");
System.out.println("3. Search for student");
System.out.println("4. Print all Students");
System.out.println("5. exit");
Scanner scanchoice = new Scanner(System.in);
choice = scanchoice.nextInt();
if (choice ==1){
Scanner scannames = new Scanner(System.in);
System.out.println("Please enter the student names into the array");
int i = 0;
for(i = 0; i<stringarray.length; i++){
String temp =scannames.nextLine();
stringarray[i]=temp.toLowerCase();
if(i==(stringarray.length-1)){
System.out.println("successfully filled up array fully");
System.out.println();
}
}
}
if(choice==2){
}
if(choice==3){
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
int x=0;
Scanner scannames1 = new Scanner(System.in);
System.out.println("Enter name of student you want to search for: ");
System.out.println();
String search=scannames1.nextLine();
String searchName=search.toLowerCase();
for(int p=0;p<20;p++){
if(searchName.equals(stringarray[p])){
x=1;
}
else{
x=0;
}
}
if(x==1){
System.out.println("We have a match in our database for "+ searchName);
}
else if (x==0){
System.out.println("No match for "+ searchName);
}
}
if (choice ==4){
System.out.println("List of names:");
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
}
}while(choice!=5);
}
}
int choice = 0;
int[] stringArray = {};
do{
String[] stringarray = new String[20];
Delete the int[] stringArray line (you don't refer to it anywhere).
Move the String[] stringarray up, outside the loop.
As to deleting, you either have to code that yourself (move everything past the deleted item up one in the array), or use one of the collection classes provided with Java (instead of a native array), which handle deletion for you.
do{
String[] stringarray = new String[20];
On each iteration of your Do { ... } loop, you're recreating the stringarray variable, thus clearing it. If you move this outside of the loop, your student entries will be maintained.
As for deleting, if you're not required to use an array of strings, I would recommend using an ArrayList. It will allow you to easily remove specific entries without worrying about the other entries. Otherwise, yes, the simplest thing to do would be to move all of the other entries down one slot to avoid gaps
Here is the corrected code:
import java.util.Scanner;
public class Lab10Ex2 {
/**
* #param args
*/
public static void main(String[] args) {
int choice = 0;
int[] stringArray = {};
String[] stringarray = new String[20];
do{
System.out.println("----------------MENU---------------");
System.out.println();
System.out.println("1. Add Students");
System.out.println("2. Delete Students");
System.out.println("3. Search for student");
System.out.println("4. Print all Students");
System.out.println("5. exit");
Scanner scanchoice = new Scanner(System.in);
choice = scanchoice.nextInt();
if (choice ==1){
Scanner scannames = new Scanner(System.in);
System.out.println("Please enter the student names into the array");
System.out.println();
int i = 0;
for(i = 0; i<stringarray.length; i++){
String temp =scannames.nextLine();
stringarray[i]=temp.toLowerCase();
if(i==(stringarray.length-1)){
System.out.println("successfully filled up array fully");
System.out.println();
}
}
}
if(choice==2){
}
if(choice==3){
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
int x=0;
Scanner scannames1 = new Scanner(System.in);
System.out.println("Enter name of student you want to search for: ");
System.out.println();
String search=scannames1.nextLine();
String searchName=search.toLowerCase();
for(int p = 0; p < stringarray.length ;p++){
if(searchName.equals(stringarray[p])){
x=1;
break;
}
else{
x=0;
}
}
if(x==1){
System.out.println("We have a match in our database for "+ searchName);
}
else if (x==0){
System.out.println("No match for "+ searchName);
}
}
if (choice ==4){
System.out.println("List of names:");
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
System.out.println();
}
}
}while(choice!=5);
}
}
Things you were doing wrong:
Instantiating the array in the do while loop.
Not breaking out of the loop if a search entity was found in the array.
Use ArrayList if you want to avoid wasting space in arrays after deletion. If you are bound to this with simple arrays, you can do this:
Place null at index from which you deleted.Create a temporary array with same size as the original one with all null values. Copy all the elements from the original array to the temporary one but skip elements that are null. Point the original array to the new array.
AND AVOID HARD CODING ARRAY LENGTHS!

Categories