AS: Avoid the physical back button Android

I want to avoid that the android users play my game and get gameover, that they simply click the back button and come back to the game.

This is my code from jumping of my GameActivity to jump into the new GameOver Activity. What a command could I use? I simply want to come back to the main activity not the gameActivity.

private void checkFails(){
    TextView failsleft = (TextView) findViewById(R.id.fails);
    if(fails < 1){
        failsleft.setText("Fails left: "+fails);
        Intent intent = new Intent(this, GameOverActivity.class);
        startActivity(intent);

    }else{
        failsleft.setText("Fails left: "+fails);
        fails--;
    }
}

Scanner class’ hasNext() on infinite loop

I’m trying to write code that uses the Scanner class to get input from the user. But hasNext(), hasNextInt(), and hasNextLine() all run into infinite loops every time.

public static void getInput(ArrayList<Double> arr){

       Scanner input = new Scanner(System.in);
       String data = "";
       String init;
       while(input.hasNextLine()){
           init = input.nextLine();
           data += init;
       }
       .
       .
       .
   }

apache camel file2 removes file while java stream is reading the file

I have a camel file2 dropbox listener to detect a file and then read other files in the same directory. Apache Camel will add a .camelLock marker when the file is detected and removes it withing few seconds.
Now the problem is, in very occasional cases my code detects the .camelLock file (as it is not deleted by camel yet) and before it finishes the following method, camel removes the file. So my method returns java.io.UncheckedIOException: java.nio.file.NoSuchFileException

Here is the documentation to camel file2: http://camel.apache.org/file2.html

private List<String> getFileNames(String fullPath) throws IOException {
        try (Stream<Path> pathStream = Files.walk(Paths.get(fullPath))) {

            return pathStream.filter(Files::isRegularFile)
                    .filter(f -> !f.toString().toLowerCase()
                            .endsWith("camellock"))
                    .map(Path::toString)
                    .map(f -> f.substring(f.lastIndexOf(File.separator) + 1, f.length()))
                    .collect(Collectors.toList());
        }

}

Any idea?

Running jar through .bat works in downloading files but not if running it directly by the .jar

I’ve written a .jar application to auto update it from my site. It works when I execute the .jar through a .bat , but when running the .jar directly, its unable to download the file from my site?

My code is:

try {
String location = getDir() + fileName;
dest = new BufferedOutputStream(new FileOutputStream(location)); 

download = url.openConnection();
readFileToDownload = download.getInputStream();
byte[] data = new byte[1024];
int numRead;
long numWritten = 0;
int length = download.getContentLength();

while ((numRead = readFileToDownload.read(data)) != -1) {
dest.write(data, 0, numRead);
numWritten += numRead;
int percent = (int)(((double)numWritten / (double)length) * 100D);
System.out.println(percent);
}

} catch (Exception exception) {
System.out.println("Download failed!");
}

I’m totally lost how the .jar works completely but just doesn’t do this function, unless I run it with a .bat (which executes the .jar)

How to make a spring boot app with tomcat embeded be able to run at weblogic?

I am trying to run my spring boot app (made through Jhipster) on a web logic server.

It works great with its embeded tomcat, but once I remove the tomcat dependency I start to see more errors.

Currently this one:

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:repackage (default) on project myproject: Execution default of goal org.springframework.boot:spr
ing-boot-maven-plugin:1.5.9.RELEASE:repackage failed: Unable to find main class -> [Help 1]

This happens after I removed

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

Is there any way I can package my app to make it run on weblogic? I am novice when talking about WL.

Any idea?

Malformed format string issue with a printf template

The assignment is to prompt for the radius of a circle, to calculate the area, and then print it using printf. I cannot get the error to go away after doing plenty of digging. Please, tell me what I’m doing wrong. The yellow error line appears below the printf template: “Area of the Circle is (%f)^2*3.14=%f..” — This template was given by the professor.

    System.out.print("Enter the radius of a circle: ");
    float circleRadius = input.nextFloat();

    float circleArea = 3.14F * circleRadius * circleRadius;

    System.out.printf("Area of the Circle is (%f)^2*3.14=%fn", circleArea);

Display recylerview Data with Aray of CustomLists

I’m a bit stuck on the following.

I’m using Retrofit and RxJava2, and I managed to get a List<List<CustomModel>> by using Observable.zip and return Arrays.asList(list1, list2, list3); it now looks like the following:

[list1,list2,list3]

I can access the lists and print each individual item using:

                for (List<CustomModel> b : customModel) {


                    for (customModel c : b) {


                        Print INDIVIDUAL ITEMS
                        Log.d("id: ", c.getId());
                        Log.d("name: ", c.getName());
                        Log.d("symbol: ", c.getSymbol());
                        Log.d("rank: ", c.getRank());



                    }

but I can’t manage to send the data to my Custom adapter using:

   recyclerAdapter = new RecyclerAdapter(getApplicationContext(), b);
                    recyclerView.setAdapter(recyclerAdapter);
                    recyclerAdapter.notifyDataSetChanged();
                    swipeRefreshLayout.setRefreshing(false);

Only gives me the latest list on the array but not the past as they get overwritten when passing the data to my recyclerview.

What will be the best way to display all 3 lists inside the recyclerView?

Trie implementation – getWords and getWordsWithPrefix

I am trying to learn and implement a Trie data structure in Java. This is not a home work I am trying to learn and implement a trie , with Arrays, as opposed to Map. I am looking for a way to get all the word in a trie, and get all the words as per the prefix , in my implementation of TrieNode

Below is my Java code

import java.util.Arrays;

public class Solution
{
  private TrieNode root;
  
  public Solution()
  {
    root = new TrieNode();
  }
  
  public void insert(String word)
  {
    TrieNode current = root;
    for(int index = 0;index < word.length();index++)
    {
      char value = word.charAt(index);
      if(!current.containsKey(value))
      {
        current.put(value, new TrieNode()); 
      }
      current = current.get(value);
    }
    current.setEnd();
  }
  
  public TrieNode searchPrefix(String word)
  {
    TrieNode current = root;
    for(int index = 0;index < word.length();index++)
    {
      char value = word.charAt(index);
      if(current.containsKey(value))
      {
        current = current.get(value);
      }
      else
      {
        return null;
      } 
    }
    return current;
  }
  
  public boolean search(String word)
  {
    TrieNode node = searchPrefix(word);
    return node != null && node.isEnd();
  }
  
  public boolean startsWith(String word)
  {
    TrieNode node = searchPrefix(word);
    return node != null;
  }
  
  public int wordCount(TrieNode root)
  {
    int result = 0;
    
    if(root.isEnd())
    {
      result++;
    }
    
    for(int index = 0;index < 26;index++)
    {
      if(root.links[index] != null)
      {
        result += wordCount(root.links[index]);
      }
    }
    return result;
  }
  
    // Return [the, there, by, bye]
  public List<String> getWords()
  {
    List<String> words = new ArrayList<String>();
    
    if(root.isEnd())
    {
      
    }
    
    for(int index = 0;index < 26;index++)
    {
      
    }
    return words;
  }
  
  // Return [by, bye] when prefix = by
  public List<String> getWords(String prefix)
  {
    List<String> words = new ArrayList<String>();
    
    if(root.isEnd())
    {
      
    }
    
    for(int index = 0;index < 26;index++)
    {
      
    }
    return words;
  }
      
    
  
  public static void main(String[] args)
  {
    Solution trie = new Solution();
    trie.insert("the");
    trie.insert("there");
    trie.insert("by");
    trie.insert("bye");
    
    System.out.println(trie.search("thee"));
    System.out.println(trie.search("the"));
    System.out.println(trie.startsWith("by"));
    System.out.println(trie.search("by"));
    System.out.println(trie.wordCount(trie.root));
  }
}

class TrieNode
{
  public TrieNode[] links;
  private final int R = 26;
  private boolean isEnd;
  
  public TrieNode()
  {
    links = new TrieNode[R];
  }
  
  public boolean isEnd()
  {
    return isEnd;
  }
  
  public void setEnd()
  {
    this.isEnd = true;
  }
  
  public boolean containsKey(char value)
  {
    return links[value - 'a'] != null;
  }
  
  public void put(char value, TrieNode node)
  {
    links[value - 'a'] = node;
  }
  
  public TrieNode get(char value)
  {
    return links[value - 'a'];
  }
}

Any inputs would be helpful.

Thanks !

Why isn’t it prohibited to access static methods in a non-static way?

Is there any possible case that calling static method in a non-static way is useful and more desirable than calling it in a static way? What is the purpose of not forbidding that practise as it might generate more confusing code? I’m aware that compiler generates warning when calling static method in an instance method way, but wouldn’t it be more clear to simply not allow that kind of situations and generate error by compiler? See these simple two examples:

public class MyClass {
    public static void test() {
        System.out.println("test");
    }

    public static void main(String[] args) {
        MyClass mc = new MyClass();
        mc.test(); // prints "test"
    }
}

Calling MyClass.test() instead of mc.test() is clear and doesn’t need any further explanations as you immediately notice that you deal with static method, when mc.test() generates a bit of confusion.

Another example is a little bit more tricky as inheritance come into play.

class Parent {
    public void test() {
        System.out.println("test in Parent");
    }
}

class Child extends Parent {
    public void test() {
        System.out.println("test in Child");
    }
}

public class MyClass {
    public static void main(String[] args) {
        Child child = new Child();
        child.test();  // prints "test in Child"

        Parent parent = new Child();
        parent.test(); // prints "test in Child"
    }
}

Due to dynamic method binding, in both cases „test in Child” is printed. But when changing test() methods to make them static, results look different (due to static method binding):

public static void main(String[] args) {
    Child child = new Child();
    child.test();  // prints "test in Child"

    Parent parent = new Child();
    parent.test(); // prints "test in Parent"
}

As we see, calling static method in a non-static way might be really confusing and be source of potential error when developer expects that the child method will be called due to polymorphism but the parent one is being called.

So, maybe a bit of curiosity:

Are there any possible situations when calling static method in a non-static way is desirable and is better than calling it in a static way?