Java: removing a specified number of elements from a queue - java

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());
}

Related

Java problems creating a new node

• 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.

Checking if two consecutive pairs of coordinates in an arraylist are equal in java

The following program should execute 10 times,each time asking the user for a pair of coordinates.I store the x and y coordinates in two separate arraylists.
The program should be able to check if a pair of coordinates has been entered more than once.A message should be printed if that happens.
My program is behaving in a peculiar fashion.Among other things,it seems to print out the message multiple times.
Secondly,say if the user enters a pair of coordinates,I want the program to print out a msg saying 'Wrong pair'.I tried inserting an else statement after the if but that doesn't work.In short,every time a pair is entered,the program should say 'wrong pair',but if a duplicate is entered,it should just say 'already entered'.How would I do that?
public static void main(String[]args)
{
Scanner a=new Scanner(System.in);
//Arraylist stores all entered x values.
ArrayList<Integer> XValues=new ArrayList<Integer>();
//Arraylist stores all entered y values.
ArrayList<Integer> YValues=new ArrayList<Integer>();
for(int i=0;i<10;i++)
{
int xval;
int yval;
System.out.println("Try no. #"+(i+1));
System.out.print("Please enter x coordinate: ");
xval=a.nextInt();
System.out.print("Please enter y coordinate: ");
yval=a.nextInt();
if(i>1)
{
for(int c=0;c<XValues.size();c++)
{
for(int d=0;d<YValues.size();d++)
{
XValues.get(c);
YValues.get(d);
if(xval==XValues.get(c) && yval==YValues.get(d))
{
System.out.println("Sorry.Already entered.\n");
}
}
}
}
XValues.add(xval);
YValues.add(yval);
}
}
Notice your nested for loops? The portion where you check your values for previous entries is being run more times than you want it to be run.
For example, when i=3, the user enters their 4th entry, and you are about to check it against the previous 3 entries. Your for(int d=0;d<YValues.size();d++) will run three times, but because it is inside the for(int c=0;c<XValues.size();c++) loop, that entire loop will run 3 times, for a total of nine times.
Remove the line for(int c=0;c<XValues.size();c++), and the corresponding brackets. In your if(xval==XValues.get(c) && yval==YValues.get(d)) line, use get(d) for both coordinates.
Also, you're checking currently for i>1, when you'll actually want to start checking once i>0.
The modified code should look as below:
public static void main(String[]args)
{
Scanner a=new Scanner(System.in);
//Arraylist stores all entered x values.
ArrayList<Integer> XValues=new ArrayList<Integer>();
//Arraylist stores all entered y values.
ArrayList<Integer> YValues=new ArrayList<Integer>();
for(int i=0;i<10;i++)
{
int xval;
int yval;
System.out.println("Try no. #"+(i+1));
System.out.print("Please enter x coordinate: ");
xval=a.nextInt();
System.out.print("Please enter y coordinate: ");
yval=a.nextInt();
if(i>0)
{
for(int d=0;d<YValues.size();d++)
{
if(xval==XValues.get(d) && yval==YValues.get(d))
{
System.out.println("Sorry.Already entered.\n");
break;
}
}
}
XValues.add(xval);
YValues.add(yval);
}
}

java array that accepts input of put name mark, quit and get name (not working)

im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}

Taking input strings and numbers into 2 arrays

Having difficulty taking in data (string and number) for participants. The idea is to create a program which will take in data into arrays (name and time separately) and eventually analyse the data by name and time
Here's my code attempt...
import java.util.Scanner;
public class RaceTimes
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Athletic Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants ");
num=input.nextInt();
// If the user enters an invalid number... display error message... ask again for valid input number
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants...");
num=input.nextInt();
}
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
for (int i = 0 ; i < nameArray.length ; i++)
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
//nameArray [1] = input.nextString();
}
}
You're nearly there!
for (int i = 0 ; i < nameArray.length ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
That should do it.
You might want to add something here to cope with values that are out of range, or things that can't be interpreted as floating point numbers. You'd need a try/catch block to catch InputMismatchException in order to deal appropriately with someone entering something that can't be interpreted as a number. (The .nextDouble() method will throw this exception if it can't parse the input.)

How do you find the index number of a string in an array in Java

I have no idea if I'm coding this efficiently, or even correctly, but I want to input a name, address, and phone number. I then want to have input find a match from the input array, and use that same index number to print the corresponding information.
import java.util.*;
public class NameAddress {
public static void main(String[] args) {
Scanner ui = new Scanner(System.in);
System.out.println("Welcome to the name collecting database");
String []names = new String[5];
String []address = new String[5];
String []phone = new String [5];
int count =0;
while (count<=5)
{
System.out.println("Please enter the name you would like to input");
names[count] =ui.next();
System.out.println("Name has been registered into Slot "+(count+1)+" :"+Arrays.toString(names));
System.out.println("Please enter the address corresponding with this name");
ui.nextLine();
address[count] = ui.nextLine();
System.out.println(names[count]+" has inputted the address: "+address[count]+"\nPlease input your phone number");
phone[count]=ui.nextLine();
System.out.println(names[count]+"'s phone number is: "+phone[count]+"\nWould you like to add a new user? (Yes or No)");
if (ui.next().equals("No"))
{
System.out.println("Please enter a name to see matched information");
String name = ui.next();
if(name.equals(names[count]))
{
System.out.println("Name: "+names[count]+"\nAddress: "+address[count]+"\nPhone: "+phone[count]);
}
count=6;
}
count++;
}
}
}
if(name.equals(names[count])) will work only if the name user is searching is at the current index of names. So you have to check every item in the array to determine whether it exists in the array. You can do this:
int itemIndex = Arrays.asList(names).indexOf(name);
if(itemIndex>=0) // instead of if(name.equals(names[count]))
{
// rest of the codes; use the itemIndex to retrieve other information
}
else
{
System.out.println(name + " was not found");
}
Or manually loop over the names array as others showed.
System.out.println("Please enter a name to see matched information");
String name = ui.next();
for(int i = 0; i <names.length;i++){
if(name.equals(names[i]))
{
System.out.println("Name: "+names[i]+"\nAddress: "+address[i]+"\nPhone: "+phone[i]);
}
}
It seems like you have data input already done.
As for data retrieval by searching, if you don't care about efficiency, then you could iterate over the entire array to see if the text inputted matches any element in your array using
int searchIndex = 0;
for (int i = 0; i < names.length; i++) {
if (searchString.equals(names[i])) {
searchIndex = i;
}
}
where searchString would be the string input by the user to find the element in the array. The code block above assumes you don't have duplicate data, but you could easily tweak the returned index to contain an array of indexes that contain your data, if you wish. You'd then have an index number (or index numbers) with which you could use to find the rest of the data in your other arrays.

Categories