Sort an arraylist by an object’s attribute or method *but by different sort orders = ABC, BCA, CAB, etc

I have a list which contains items which have a variable which contains which may be 1 of 3 different values.
I want to be able to sort the list according to the value given so that the list will end up as: [b,b,b, c,c,c, a,a,a] or any pattern of my choosing.
(where b, c, or a is a representation of itemType of MyItem see code below.)

The sorted list would end up as [MyItem, MyItem, MyItem …and so on] just sorted so that MyItem with itemType = b comes first, then with type c comes second, then with type a comes third.

Maybe a better way to describe what I want is grouping or sorting in groups?

public class MyItem {
    // possible values for item type
    public static final int ITEM_TYPE_A = 0x0;
    public static final int ITEM_TYPE_B = 0x1;
    public static final int ITEM_TYPE_C = 0x2;

    protected int itemType; 

public class ArrayThing {
    ArrayList<MyItem> list;

    public void sortBy(int sortOrder) {
        /* sort items in list by sortOrder takes a 3 digit int     
           representing the order examples: 123 = ABC, 321 = CBA
        switch(sortOrder) {
            case(123): do sort stuff here // sort by order ABC
            case(132): do sort stuff here // sort by order ACB
            case(231): do sort stuff here // sort by order BCA
            /* and so on */

How can I easily do this?

Hopefully this explains what I want to do pretty clearly. If not I’m more than willing to clarify 🙂

problems with String,stringBuilder, methods,instances

i’m a student doing my first course in javascript and was given a workshop question.

Using instance class and methods, i have to create a program that runs a hangman game.

The hangman game will run 3 times, each with a different word.

If the word is ‘hello’, it will be encrypted into ‘?????’.

When i guess ‘h’, it will display “h????’.

So far i’ve managed to put question marks on my hidden word and convert the word that has the same char as contained in the word:

 String word = "hangman";

  StringBuilder hiddenWord = new StringBuilder("???????");

  char input;

  input = keyboard.nextLine().charAt(0);

   for(int i=0; i<word.length(); i++)
     if(word.charAt(i) == input)

The question wants me to use method getDisguisedWord to return a string containing correctly guessed letters in their correct position and unknown letters replaced with ‘?'(which is similar to what i did above).

however, i have no idea how to do so.

if i remember correctly, a string cannot be created as a method because it is not a primitive type(i may be wrong)

this is my class file

 import java.util.Scanner;
public class hangman {
Scanner keyboard = new Scanner(;
private String secretWord ="hello";
StringBuilder hiddenWord = new StringBuilder("?????");
private int numberOfGuess = 0;
private int numberOfwrongGuess = 0;    
public void makeGuess(char input ) //get ch input

{System.out.println("Input: ");
input = keyboard.nextLine().charAt(0); }

public StringBuilder getDisguisedWord(StringBuilder word)
{ return a string containing correctly guessed letters in their correct 
position and unknown letters replaced with '?' }

public String getSecretWord(String secretWord)
{ return Hidden word }

public int getGuessCount(int numberOfGuess)
{ return no of guess made}

public boolean isFound(boolean found)
{ return true if hidden word is discovered}

just need to be steered in the right direction

JMenuBar not showing at all

I got this code

  public ELibrary(){
  public void createMenuBar(){
    menuBar = new JMenuBar();
    file1 = new JMenu();
    newfile = new JMenuItem();

can someone help me explain why the menubar is not showing at all ? i already declared the menuBar and file1 as menu and newfile as menuItems on the start of the class

Error : Attempt to invoke virtual method ‘ ‘ on a null object reference [duplicate]

This question already has an answer here:

I know this type of question has already been posted . But they didn’t help me .

Here I am trying to retrive the records from my online firebase database .

 public Records read_info(String email)
    Log.i("In the database class","Records readinfo");
    Log.i("Read Successfull","Himanshu"+email);
    final Records[] record = {null};

    myRef.child(email).addValueEventListener(new ValueEventListener() {
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.

            record[0] = dataSnapshot.getValue(Records.class);


        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.i("Failed to read value.", " ");
    return record[0];


protected void onCreate(Bundle savedInstanceState) {

    Records records = read_info("a");

Error that I am getting is

phombp.firebaserealtimedatabaseaccess E/AndroidRuntime: FATAL EXCEPTION: main
Process: phombp.firebaserealtimedatabaseaccess, PID: 11711
java.lang.RuntimeException: Unable to start activity ComponentInfo{phombp.firebaserealtimedatabaseaccess/phombp.firebaserealtimedatabaseaccess.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String phombp.firebaserealtimedatabaseaccess.Records.getName()’ on a null object reference
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(
at java.lang.reflect.Method.invoke(Native Method)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String phombp.firebaserealtimedatabaseaccess.Records.getName()’ on a null object reference
at phombp.firebaserealtimedatabaseaccess.MainActivity.read_info(
at phombp.firebaserealtimedatabaseaccess.MainActivity.onCreate(
at android.os.Handler.dispatchMessage( 
at android.os.Looper.loop( 
at java.lang.reflect.Method.invoke(Native Method) 

Structure of JSON in the database is :

JSON Structure

enter image description here

filter a list of object by its list field

There are two plain objects for Student and Course like this:

public class Student {
    List<Course> courses;
public class Course {
    String name;

If we have a list of Students, how can we filter some of students by the name of their courses?

  • first I try flatMap to answer this question, but it returns course
    objects instead student objects.
  • then I use allMatch (following codes).
    however it returns Student list but the List always is empty. What is the
List<Student> studentList;
List<Student> AlgorithmsCourserStudentList =
    filter(a -> -> c.getCourseName.equal("Algorithms"))).

Connecting to ESP8266 from android device using socket

Im trying to connect to my ESP8266 on a local network via TCP socket initiated from android. The ip address of ESP changes everytime I restart my router thereby I gave it “esp.local” hostname.
Is there any way to connect to the ESP directly from android not via ip address but through local hostname.

What might be a simpler way to code this?

I’m writing a program that allows students to calculate the average number of students in each of their classes. At the moment, my code looks like this:

(double classes is the number of classes the student is taking, and the number of students in each class is assigned to class1, class2, etc.)

if (classes == 1) {
    System.out.printf("How many students are there in your 1 st class?%n");
    class1 = TextIO.getlnDouble();
    classes = classes + 1;
    System.out.printf("Do you have another class?");
    boolean response = TextIO.getlnBoolean();
  } else if (classes == 2);

et cetera, for all 9 possible classes. (My school only allows the credit equivalent of 6.5 classes to be taken in a single semester, but some of that may be made up of two-credit or non-credit classes.)

I could just make a loop out of this, but how would I assign the given number to the correct double? i.e. how could I swap out class1 for class2, class3, etc.?

A jar file can rename or delete itself at run time?

I’m looking a solution to rename or delete a jar file by itself at run time. I have some tries such as using a batch file which runs script to rename the jar file just before System.exit(0) command:

public class Test {

    public static void main(String[] args) {
        System.out.println("********start jar file*****");
        try {
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);

The batch file is contain below scripts:

cd c:usersuser
ren "path to jar file" newName.jar

But, it cannot rename the jar file.

Button Inside Fragment won’t work even without errors

My CALCULATE button won’t work & it’s inside a fragment. there are no errors and I don’t know what’s wrong wt it. can someone help? thank you!

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.genapp, container, false);

btnCalculate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View rootView) {
            try {
                WattDouble = Double.parseDouble(etWattage.getText().toString());
                BillAmountS = etBillAmt.getText().toString();
                BillAmount = Double.parseDouble(BillAmountS);
                if (BillAmount >= 0 && BillAmount <= 108) {
                    PKwh = KWh[0];
                } else if (BillAmount >= 109 && BillAmount <= 338) {
                    PKwh = KWh[1];
                } else if (BillAmount >= 339 && BillAmount <= 573) {
                    PKwh = KWh[2];
                } else if (BillAmount >= 574 && BillAmount <= 1021) {
                    PKwh = KWh[3];
                } else if (BillAmount >= 1022 && BillAmount <= 2109) {
                    PKwh = KWh[4];
                } else if (BillAmount >= 2110 && BillAmount <= 3271) {
                    PKwh = KWh[5];
                } else if (BillAmount >= 3272 && BillAmount <= 4625) {
                    PKwh = KWh[6];
                } else if (BillAmount >= 4626 && BillAmount <= 7684) {
                    PKwh = KWh[7];
                } else if (BillAmount >= 7685) {
                    PKwh = KWh[8];
                } else {
                    Toast.makeText(getActivity().getApplicationContext(), "Invalid Amount", Toast.LENGTH_LONG);
               //formula /*Cost per hour = Rate x [(appliance wattage x 0.8 x 0.8) + (appliance wattage x 0.2)] / 1000)*/
                CPH = PKwh * (WattDouble / 1000);
                CPD = CPH * hrfrm;
                CPW = CPD * dfrm;
                CPM = CPW * wfrm;

                etHour.setText("PhP " + String.format("%.2f", CPH));
                etDay.setText("PhP " + String.format("%.2f", CPD));
                etWeek.setText("PhP " + String.format("%.2f", CPW));
                etMonth.setText("PhP " + String.format("%.2f", CPM));
            } catch (NumberFormatException e) {
                Toast.makeText(getActivity().getApplicationContext(), "Invalid Entry", Toast.LENGTH_LONG);


    return rootView;

the original view on the on click was: (view v) and I read something off the internet saying it should be the same name as my inflater.inflate so I changed it to (view rootView). nothing happened to both of them. button still wont work. thank you!