I'm working on my school project and one of my idea was to create a to-do list by asking
Step 1. Enter your event
Step 2. user enters
Step 3. Enter your due date (decimal form)
Step 4. user enters
Step 5. Ask if user wants to enter more events (1 for yes, 0 for no)
Step 6. while user didn't enter 0, repeat the process 1-5
Then I want my code to sort my event according to my due date. I found something on StackOverflow that works for my program but I have the following problems:
When I run my program the system shows:
Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
I've no idea why and hope this to be solved.
When I run my program, Step 2 is skipped after the first event is entered
Which means only 1 event and due date is entered, then you can only enter due dates.
I've no idea how this line of code works
Collections.sort(sortedList, Comparator.comparing(s -> arr_dues[stringListCopy.indexOf(s)]));
Which I should be able to understand if I'm submitting this. If you can, can you please explain a little about comparators or drop a link for a video that I would be able to watch to understand this concept.
Thank you very very very much. Here is my code.
static void to_do() {
int more = -1;
String event;
double due = 0.0;
Scanner in = new Scanner(System.in);
ArrayList<String> events = new ArrayList <String>();
ArrayList<Double> dues = new ArrayList <Double>();
System.out.println("To-Do List Generator:");
while (more != 0) {
System.out.println("Please enter your event");
event = in.nextLine();
events.add(event);
System.out.println("Please enter the due date in decimal form");
due = in.nextDouble();
dues.add(due);
System.out.println("Do you have more events to add? Yes enter 1, No enter 0");
more = in.nextInt();
}
System.out.println("Entry Successful. Here is your to do list");
String[] arr_events = new String[events.size()];
double[] arr_dues = new double[dues.size()];
for (int i=0; i<events.size();i++){
arr_events[i] = events.get(i);
}
for (int i=0; i<dues.size();i++){
arr_dues[i] = dues.get(i);
}
final List<String> stringListCopy = Arrays.asList(arr_events);
ArrayList<String> sortedList = new ArrayList(stringListCopy);
Collections.sort(sortedList, Comparator.comparing(s -> arr_dues[stringListCopy.indexOf(s)]));
String[] returnarr = new String[stringListCopy.size()];
Collections.sort(dues);
for (int i = 0; i<stringListCopy.size(); i++) {
returnarr[i] = sortedList.get(i);
}
for (int i = 0; i<arr_dues.length; i++) {
System.out.print(returnarr[i] + ", Due: ");
System.out.println(dues.get(i));
}
}
public static void main(String[] args) {
to_do();
}
Standard usage would be:
List<String> sortedList = new ArrayList<>(stringListCopy)
The issue here is likely in handling newlines. When you call in.nextInt() it is reading an integer from System.in but it is not reading the final newline which is then read by in.nextLine(). Try printing the value you are reading to see what it's doing.
Read the standard tutorial on sorting and lambdas. In summary, Collections.sort takes a Comparator. The Comparator interface has a number of static methods used to create comparators. Comparator.comparing creates a comparator that compares a value generated by a Function. Function is a functional interface so it can take a lambda. The statement you show can be interpreted as: sort the sortedList collection according to the natural ordering of values generated from each entry using the expression arr_dues[stringListCopy.indexOf(s)].
Also note that a much better design would be to encapsulate each event in a single object:
class Event {
private final String name;
private final LocalDate dueDate;
}
And have a single list of events:
List<Event> toDoList = new ArrayList<>();
The copying between collections and arrays is really not necessary.
Related
I have created an Array holding [24] data, and I assigned some information in each index. my problem is when I want to call the indexes using Scanner from the keyboard, let's say I called index[12] from the user, next time I call it I want it to say, u already selected that number, choose a different number so on so forth. basically, I shouldn't call the same index twice, what is the best thing to use.
your help is much needed.
Use a java.util.Set to store the selected indexed, for exmaple, java.util.HashSet.
It should look like:
Set<Integer> selected = new HashSet<>();
int userInput = ...; // get input from user
while (selected.contains(userInput)) {
// print u already selected that number, choose a different number so on so forth
userInput = ...; // get input from user
}
selected.add(userInput);
// do something with the index
You must save the index of selected numbers, and then you make a comparison of all new numbers with your list's elements.
Scanner s = new Scanner (System.in);
int choice = s.nextInt();
List<Integer> choiced = new ArrayList<Integer>();
while (true) {//or your condition
label:
for (Integer i : choiced) {
if (choice == i) {
System.out.println("Index already selected, please select a different one");
break label;
}
}
choiced.add(choice);
choice = s.nextInt();
}
I tried both of your ways but still could solve it here is my code how would u have applied the codes that u guys wrote in here.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number = 0;
String [] differentChocolate = new String[24];
differentChocolate[0] = "You receive: A star that weighs 7 grams";
differentChocolate[1] = "You receive: Praline Bag Assorted 800g";
differentChocolate[2] = "You receive: Kinder Surprise Santa 75g";
differentChocolate[3] = "You receive: Woolworths Christmas Chocolate Net Bag 72g";
differentChocolate[4] = "You receive: Quality Street Tub 726g";
differentChocolate[5] = "You receive: Cadbury Favourites Snowman Bowl 700g";
differentChocolate[6] = "You receive: Lindt Santa Pouch Bag 80g";
differentChocolate[7] = "You receive: Praline Bag Assorted 800g";
while (true){
System.out.println("Choose a chocolate (0-23): ");
number = in.nextInt();
System.out.println(differentChocolate[number]);
}
}
}
I am trying to generate an arraylist in java by first inputting the default size desired of the said arraylist. Then I want to get the user to input the string to fill the arraylist. I have made one that almost works. The only problem is that for some reason I get a default value at the start.
For example, if I set the list length to 3 the list returned is: [,example,value,here]. I understand a value of 3 means 4 values in a list but I feel like that just doesn't look too nice. The problem I think lies in the way I set the size of the list but I don't see any other way.
When I set the list value manually in the for loop I don't get this problem. It only happens when I want the user to input the length. Where is the small error?
import java.util.*;
public class ListsPractice {
public static void main(String[] args) {
Scanner userin = new Scanner(System.in);
System.out.println("Enter length of desired list: ");
int lenlist = userin.nextInt();
ArrayList list1 = new ArrayList();
for(int counter = 0; counter <= lenlist; counter++) {
System.out.println("Enter an element: ");
String value=userin.nextLine();
list1.add(value);
}
System.out.println("the result is: "+list1.subList(1, lenlist+1));
}
}
I am new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}
I'm trying to write a program in which the user inputs their grocery list then based upon the type of item it is the program will give you a good order to shop for your items(i.e puts the meats together and the vegetables together)
here's my current problem, I can't get the user input to compare to the multiple string type arrays I have of store items.
String[] VegiFruit = {"Apples", "Lettuce", "Broccoli"};
String[] Meats = {"Ground beef", "Hambuger"};
Scanner USER_IN = new Scanner(System.in);
Methods Use = new Methods(); //This is another class I have, it just makes printing empty lines and lines of **** look nicer
Use.border();
System.out.println("Enter Item name then follow instructions.");
Use.space();
System.out.print("Item 1: ");
String InptOne = USER_IN.nextLine();
}
for (int i = 0; i < VegiFruit.length; i++)
{
if(Arrays.asList(VegiFruit).contains(InptOne))
{
System.out.println("Item is a VEGI");
}
}
for(int p = 0; p < Meats.length; p++)
{
if(Arrays.asList(Meats).contains(InptOne))
{
System.out.println("Item is a MEAT");
}
}
you need not go through the loops as contains method will compare with all the elements in the list.
I ran your code and the below works fine.
if(Arrays.asList(VegiFruit).contains(InptOne))
{
System.out.println("Item is a VEGI "+InptOne);
}
if(Arrays.asList(Meats).contains(InptOne))
{
System.out.println("Item is a MEAT "+InptOne);
}
However, please note that this is case senstive comparison and if the user does not enter the vegetable in your format then it will not work.
To solve that problem, you can take 2 approaches:
Have the list of veegetables/meat in caps and make the input.toUpperCase() before comparing it in contain method.
2.Use the answer on Array contains() without case sensitive lookup?
I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.