Java Programs - Incorporating Logical Thinking - Basic

Factorial Program:

package javaBasics;
import java.util.Scanner;

public class Test  {
static int temp=1;
  public static int FirstFactorial(int num) {
    // code goes here
num=num!=1?(num*FirstFactorial(num-1)): 1;
return num;
  }

  public static void main (String[] args) {
    // keep this function call here   
    Scanner s = new Scanner(System.in);
    System.out.print(FirstFactorial(s.nextInt()));
  }

}


Logical Construct:

Iterate the loop until a certain condition is reached using Ternary operator
Example: Input 5 on the Keyboard 
5->4->3->2->1[exit]
1 ->num*FirstFactorial(num-1)
2 ->num*(num-1)*FirstFactorial([num-1]-1)
->num*(num-1)*(num-2)*FirstFactorial([[num-1]-1]-1)
4 ->num*(num-1)*(num-2)*(num-3)*FirstFactorial([[[num-1]-1]-1]-1) 
               =>5*4*3*2*FirstFactorial(1) => 5*4*3*2*1 =>120

FirstFactorial(1) ->1



Reverse a String

Solution 1:

public class Reverse {
public static String FirstReverse(String str) {
      String inStr;
      char x;
   
      inStr = str;
      str="";
   
      for(int i = 0; i < inStr.length(); i++){
          x=inStr.charAt(i);
          str = x+str;
//str=str+x; -> gives the same string

      }

  return str;
    
  } 
  
  public static void main (String[] args) {  
    // keep this function call here     
    Scanner s = new Scanner(System.in);
    System.out.print(FirstReverse(s.nextLine())); 
  }   
  


Logical Construct
example input: Test in pro
str = t
str=e+t =>et
str=s+et =>set
str=t+set =>tset
str= +tset => tset
str=i+ tset=>i tset
.......
....
str= orp ni tset

Solution 2:

public class Reverse {
public static String FirstReverse(String str) {

return new StringBuilder(str).reverse().toString();  
  } 
  
  public static void main (String[] args) {  
    // keep this function call here     
    Scanner s = new Scanner(System.in);
    System.out.print(FirstReverse(s.nextLine())); 
  }   
  

Find the Longest Word in a String:

public static String LongestWord(String sen) {

//Solution 1 - Using Steams

// return Arrays.stream(sen.split("
 ")).max(Comparator.comparingInt(String::length)).orElse(null).toString();

//Solution 2

int maxIndex = 0;
split = sen.split("[^a-zA-Z]");
for (int i = 1; i < sen.split("[^a-zA-Z]").length; i++) {
//assume word at '0' index is max & then compare with rest 
if ((sen.split("[^a-zA-Z]"))[i].length() > sen.split("[^a-zA-Z]")[maxIndex].length())
//if not then make index at 'i' as Max  
maxIndex = i;
}
return sen.split("[^a-zA-Z]")[maxIndex];
}

public static void main(String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LongestWord(s.nextLine()));

}

Comments

Popular posts from this blog

QA's approach 2 Java - Understanding Static context

Selenium 4 absolute beginners - How to create Batch execution file

Technologies - Log4J - Create Log4j Configuration File - Where ? How ? What ?