Click here to Skip to main content
16,020,381 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I'm trying to create a note-taking app that gives every note an incremented number starting from 1, my question is how to increment the "count" variable in "addNote()" method so it's get increased every time an entry is put inside the map and give each entry a number bigger by one than the previous number?

Java
public class Main {
    static Scanner scanner = new Scanner(System.in);
    static Map<Integer,String> myNotes = new HashMap<>();

    public static void main(String[] args) {
        
    }

    public static boolean addNote() {
        System.out.println("Enter a note to added ");
        String note = scanner.nextLine();
        if (myNotes.containsValue(note)) {
            System.out.println("Note " + note + " already exists");
            return false;
        }
        int count=1;
        myNotes.put(count,note);
        System.out.println("Note added successfully");
        return true;
    }


What I have tried:

i didn't know what to do, i tried some ways but it didn't worked.
Posted
Updated 22-Jun-19 23:13pm
v3

1 solution

Take your count variable outside the function—because of the scoping in Java, that variable gets deleted and refreshed as 1 each time you call the function to add the note, which then leads to update of the value for that key, which is 1.

Java
static int count = 1; // needs to be static to be accessible in static context.

public static boolean addNote() {
    System.out.println("Enter a note to added ");
    String note = scanner.nextLine();
    if (myNotes.containsValue(note)) {
        System.out.println("Note " + note + " already exists");
        return false;
    }

    // use the current value, but update for next call!
    myNotes.put(count++, note); 
    System.out.println("Note added successfully");
    return true;
}
Now this will work as you are expecting it to. Now in the main you can call the function multiple times.

Please check these links for more on this topic,
Interesting facts about Increment and Decrement operators in Java - GeeksforGeeks[^]
Scope of Variables In Java - GeeksforGeeks[^]
 
Share this answer
 
Comments
hiwa doski 23-Jun-19 7:08am    
Thank you so much.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900