I have written this:
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();//declare your list
Scanner input = new Scanner(System.in);//create a scanner
System.out.println("How many participants? ");
int nbr = input.nextInt();//read the number of element
input.nextLine();
do {
System.out.println("What is the name of the people?");
list.add(input.nextLine());//read and insert into your list in one shot
nbr--;//decrement the index
} while (nbr > 0);//repeat until the index will be 0
System.out.println(list);//print your list
The output is:
Jack, Frank
What I want to do is changing the content of the linked list. For example I wrote 2 names Jack and Frank. Then I want to add Jack's surname so that linked list will be:
Jack Adam, Frank
What should I do?
What you need to do is use the set method updating the specific position that you want to update. In this case will be something like this:
list.set(0, list.get(0) + " Adam");
Notice that we are getting the content of the position 0 of the list and concatenating with the surname.
Related
I have an ArrayList with student grades and I want to filter students with the given grade letter. For example, if the user enters A the table must show all the students with the F grade. But the problem is it does not filter it.
static List<Assign2> studentList = new ArrayList<>();
String letter = JOptionPane.showInputDialog(this,"Which grade do you want to filter?");
List<Assign2> remaining = new ArrayList<>(studentList);
for(int i=0;i<remaining.size();i++){
if(remaining.get(i).getLetterGrade()!=letter){
remaining.remove(i);
}
}
table(remaining);
What about something like this:
if(letter.equalsIgnoreCase("A")){
List<Strudents> sList = studentList.stream()
.peek(s -> System.out.println(s.getLetterGrade())) // just for debugging purpose
.filter(s -> s.getLetterGrade().contains("A")) // why not equals? Is it one letter only?
.collect(Collectors.toList());
}
You can do some pre calculation. Like you can group all the students whose grade are same and put them in hashmap. When you will get an query just get the list of the students from the map.
Another option with out using
studentList.get(i).getLetterGrade().contains("A")
use
studentList.get(i).getLetterGrade().equalsIgnoreCase("A")
You could use following java8 snippet to filter out all grades which are not equal to the input:
// create copy
List<Assign2> remaining = new ArrayList<>(studentList);
// remove all that do not have the input grade
remaining.removeIf(e -> !e.getLetterGrade().equals(letter));
The above code first creates a copy of the original list. And then uses that copy, to remove all students which don't have the grade the user entered.
Note: the original list will still be the same. So it still contains all Students
This answer is based on what i understood in your question.
try like this. for each student you need to check if he hasn't the entered grade letter, if so you add him to the list.
String letter = JOptionPane.showInputDialog(this,"Which grade do you want to filter?");
for(int i=0;i<studentList.size();i++){
if(!studentList.get(i).getLetterGrade().equalsIgnoreCase(letter)){
sList.add(studentList.get(i));
}
}
import java.util.*;
public class PersonList{
public static void arraylist() {
// create an array list
ArrayList Employee = new ArrayList();
// add elements to the array list
Scanner input = new Scanner (System.in);
System.out.println("Name: ");
Employee.add(input.next());
System.out.println("Year of birth: ");
Employee.add(input.next());
System.out.println("");
Employee.add(input.next());
System.out.println("");
Employee.add(input.next());
System.out.println("");
Employee.add(input.next());
System.out.println("Contents of al: " + Employee);
}
}
I have an arraylist that takes user entered data and I need to store data that has a space into one block.
I haven't added the other things that I will include. I want to be able to put a name such as "John Smith" into the Name, instead of it printing John, Smith in two separate blocks. I am very new to programming and I apologize if it is sloppy and/or annoying.
Replace input.next() with input.nextLine(). The former will usually split your input based on whitespaces, whereas the latter will give you the whole line.
On a side note, there is a naming convention for variables, which requires them to start with a lowercase letter. Moreover, it is discouraged to use raw types for lists and it is prudent to always explicitly specify the type. You can change the whole arraylist creation line to something like ArrayList<String> employees = new ArrayList<>();.
I am trying to create code where the user gets to input whether they want to add a number to a linked list. Every time they add a number, the new linked list gets displayed showing the collection of numbers. Here is the first class:
public class Test {
public static void main(String[] args) {
while(true)
{
LinkedList<Integer> list = new LinkedList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Enter command: ");
String userInput = scan.nextLine();
String [] parts = userInput.split(" ");
String part1 = parts [0];
String part2 = parts[1];
int num = Integer.parseInt(part2);
if (part1.equals("add"))
{
Set test = new Set();
test.addNext(num);
list.add(num);
System.out.println(list.toString());
}
}
}
}
Is there a way to make the list print out like this:
Enter command: add 5
5
Enter command: add 8
8 5
Enter command: add 6
6 8 5
Move
LinkedList<Integer> list = new LinkedList<Integer>();
Scanner scan = new Scanner(System.in);
Outside the while loop, because every iteration list is getting overridden by a brand new one, so naturally it will have only one element every time you print it.
It also seems you want to display the list in reverse order. Normally when you add elements, they are placed at the end of the list. You should use addFirst() to put them at the beginning and get your expected output.
Trying to sort the doubles in descending order from my .txt file and print out the results, but why am I getting 4 lines of []?
My text file looks like this:
Mary Me,100.0
Hugh More,50.8
Jay Zee,85.0
Adam Cop,94.5
with my code that looks like this:
public static void sortGrade() throws IOException
{
Scanner input = new Scanner(new File("Grades.txt"));
while(input.hasNextLine())
{
String line = input.nextLine();
ArrayList<Double> grades = new ArrayList<Double>();
Scanner scan = new Scanner(line);
scan.useDelimiter(",");
while(scan.hasNextDouble())
{
grades.add(scan.nextDouble());
}
scan.close();
Collections.sort (grades,Collections.reverseOrder());
System.out.println(grades);
}
input.close();
}
I'd like for the output to look like this:
Hugh More,50.8
Jay Zee,85.0
Adam Cop,94.5
Mary Me,100.0
A push in the right direction would be great, thanks.
The problem is you're not reading in your values correctly!
You're reading in your line here:
String line = input.nextLine();
And then trying to parse it with a second one but this:
scan.hasNextDouble()
Will always return false as the first token in each string is the name! And it's not a double. You need to change the way you're parsing your input.
Furthermore if you want to sort both the name and the score at the same time you have to create an object that would encapsulate both name and grade and implement Comparable or write a custom Comparator for that type. Otherwise you'd have to make a Map mapping grade to each name, sort the grades and then print it in order while getting names for each grade (there can be multiple names for the same grade). This is not recommended because it does look clumsy.
Writing a comparable class really isn't that hard you just need to implement one method :-)
#Edit: you don't need a second scanner, if your format is set and that easy just use a split on that line like this:
String[] gradeName = line.split(",");
grades.add(Double.parseDouble(gradeName[1]));
If you can have more than 1 grade per person than instead of just getting gradeName[1] iterate over gradeName starting from the element at index 1 (since 0 is the name).
#Edit2:
You are creating a new grades list in the loop every time, so it will read one entry, add it to the list, sort it and print it. You should pull out everything except for those lines outside the while loop:
String line = input.nextLine();
String[] gradeName = line.split(",");
grades.add(Double.parseDouble(gradeName[1]));
#Edit3:
If you want an ascending order don't use Collections.reverseOrder(), just the default one:
Collections.sort (grades);
I need to write a program that helps determine a budget for "peer advising" the following year based on the current year. The user will be asked for the peer advisor names and their highest earned degree in order to determine how much to pay them. I am using a JOptionPane instead of Scanner and I'm also using an ArrayList.
Is there a way for the user to input both the name and the degree all in one input and store them as two different values, or am I going to have to have two separate input dialogs? Example: storing the name as "Name1" and the degree as "Degree1 in order to calculate their specific pay.
Also, I am using an ArrayList but I know that the list will need to hold a maximum of six (6) elements, is there a better method to do what I am trying to do?
Here is what I had down before I started thinking about this, if it's necessary.
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class PeerTutoring
{
public static void main(String[] args)
{
ArrayList<String> tutors = new ArrayList<String>();
for (int i = 0; i < 6; i++)
{
String line = null;
line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
String[] result = line.split("\\s+");
String name = result[0];
String degree = result[1];
}
}
}
"Is there a way for the user to input both the name and the degree all
in one input, but store them as two different values."
Yes. You can ask the user to enter input separated with space for example, and split the result:
String[] result = line.split("\\s+"); //Split according to space(s)
String name = result[0];
String degree = result[1];
Now you have the input in two variables.
"I decided to use ArrayList but I know the number of names that will be inputed (6), is there a more appropriate array method to use?"
ArrayList is fine, but if the length is fixed, use can use a fixed size array.
Regarding OP update
You're doing it wrong, this should be like this:
ArrayList<String[]> list = new ArrayList<String[]>(6);
String[] splitted;
String line;
for(int i=0;i<6;i++) {
line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
splitted = line.split("\\s+");
list.add(splitted);
}
for(int i=0;i<6;i++)
System.out.println(Arrays.deepToString(list.get(i))); //Will print all 6 pairs
You should create an ArrayList that contains a String array that will represent the input (since the user enters pair as an input). Now, all what you have to do is to insert this pair to the ArrayList.
What you can do is store the input from you JOptionPane in a String, and then split the String into an array to store the name and degree entered. For example:
String value = null;
value = JOptionPane.showInputDialog("Please enter tutor name and
their highest earned degree.");
String[] tokens = value.split(" ");//if you input name followed by space followed by degree, this splits the input by the space between them
System.out.println(tokens[0]);//shows the name
System.out.println(tokens[1]);//shows the degree
Now you can use tokens[0] to add the name to your List.