Search the Whole World Here.,.,

How do I convert string to an integer or number?

How do I convert string to an integer or number?

package org.kodejava.example.lang;
public class StringToInteger {
public static void main(String[] args) {

// Some random selected number, could representing a decimal,
// hexadecimal or octal number.

String myLuckyNumber = "13";

// We convert a string to an integer by invoking parseInt() method
// of the Integer class.

Integer number = Integer.parseInt(myLuckyNumber);
System.out.println("My lucky number is: " + number);

// We can also converting a string representation of a number other
// then the decimal base, for instance an hexadecimal by providing
// the radix to the method.

number = Integer.parseInt(myLuckyNumber, 16);
System.out.println("My lucky number is: " + number);
number = Integer.parseInt(myLuckyNumber, 8);
System.out.println("My lucky number is: " + number);
}
}

Our code results are:

My lucky number is: 13
My lucky number is: 19
My lucky number is: 11


Source : https://kodejava.org/how-do-i-convert-string-to-an-integer-or-number/
How do I reverse a string?

How do I reverse a string?

Below is an example code that reverse a string. In this example we useStringBuffer.reverse() method to reverse a string. In Java 1.5, a new class calledStringBuilder also has a reverse() method that do just the same, one of the difference is StringBuffer class is synchronized while StringBuilder class is not.
And here is the string reverse in the StringBuffer way.
package org.kodejava.example.lang;

public class StringReverseExample {
    public static void main(String[] args) {
        // The normal sentence that is going to be reversed.
        String words =
                "Morning of The World - The Last Paradise on Earth";

        // To reverse the string we can use the reverse() method in
        // the StringBuffer class. The reverse() method returns a
        // StringBuffer so we need to call the toString() method to
        // get a string object.
        String reverse = new StringBuffer(words).reverse().toString();

        // Print the normal string
        System.out.println("Normal : " + words);
        // Print the string in reversed order
        System.out.println("Reverse: " + reverse);
    }
}
Beside using this simple method you can try to reverse a string by converting it to character array and then reverse the array order.
And below is the result of the code snippet above.
Normal : Morning of The World - The Last Paradise on Earth
Reverse: htraE no esidaraP tsaL ehT - dlroW ehT fo gninroM

Source : https://kodejava.org/how-do-i-reverse-a-string/

How do I iterate each characters of a string?

How do I iterate each characters of a string?

package org.kodejava.example.text; import java.text.CharacterIterator; import java.text.StringCharacterIterator; public class StringCharacterIteratorExample { private static final String text = "The quick brown fox jumps over the lazy dog"; public static void main(String[] args) { CharacterIterator it = new StringCharacterIterator(text); int vowels = 0; int consonants = 0; // Iterates charater sets from the beginning to the last character for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { vowels = vowels + 1; } else if (ch != ' ') { consonants = consonants + 1; } } System.out.println("Number of vowels: " + vowels); System.out.println("Number of consonants: " + consonants); } }




Source :https://kodejava.org/how-do-i-iterate-each-characters-of-a-string/
How do I add leading zeros to a number?

How do I add leading zeros to a number?

This example shows you how to use the String.format() method to add zero padding to a number. If you just want to print out the result you can use System.out.format(). This method is available since Java 1.5, so If you use a previous version you can use the NumberFormat class, see: How do I format a number with leading zeros?.


package org.kodejava.example.lang; public class LeadingZerosExample { public static void main(String[] args) { int number = 1500; // // String format below will add leading zeros (the %0 syntax) // to the number above. The length of the formatted string will // be 7 characters. // String formatted = String.format("%07d", number); System.out.println("Number with leading zeros: " + formatted); } }


Here is the result of the code snippet above:

Number with leading zeros: 0001500

Source : https://kodejava.org/how-do-i-add-leading-zeros-to-a-number/
How do I convert InputStream to String?

How do I convert InputStream to String?

This example will show you how to convert an InputStream into String. In the code snippet below we read a data.txt file, could be from common folder or from inside a jar file.


package org.kodejava.example.io; import java.io.*; public class StreamToString { public static void main(String[] args) throws Exception { StreamToString sts = new StreamToString(); // Get input stream of our data file. This file can be in // the root of you application folder or inside a jar file // if the program is packed as a jar. InputStream is = sts.getClass().getResourceAsStream("/data.txt"); // Call the method to convert the stream to string System.out.println(sts.convertStreamToString(is)); } public String convertStreamToString(InputStream is) throws IOException { // To convert the InputStream to String we use the // Reader.read(char[] buffer) method. We iterate until the // Reader return -1 which means there's no more data to // read. We use the StringWriter class to produce the string. if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader( new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } return ""; } }



Source : https://kodejava.org/how-do-i-convert-inputstream-to-string/
WordCount

WordCount

Program  that compares counting words in files using an ArrayList and a Map.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

import javax.swing.JFileChooser;
import javax.swing.UIManager;


public class WordCount {

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


    // allow user to pick file to exam via GUI.
    // allow multiple picks
    public static void countWordsViaGUI() {
        setLookAndFeel();
        try {
            Scanner key = new Scanner(System.in);
            do {
                System.out.println("Opening GUI to choose file.");
                Scanner fileScanner = new Scanner(getFile());
                Stopwatch st = new Stopwatch();
                st.start();
                ArrayList words = countWordsWithArrayList(fileScanner);
                st.stop();
                System.out.println("time to count: " + st);
                System.out.print("Enter number of words to display: ");
                int numWordsToShow = Integer.parseInt(key.nextLine());
                showWords(words, numWordsToShow);
                fileScanner.close();
                System.out.print("Perform another count? ");
            } while(key.nextLine().toLowerCase().charAt(0) == 'y');
            key.close();
        }
        catch(FileNotFoundException e) {
            System.out.println("Problem reading the data file. Exiting the program." + e);
        }
    }


    // determine distinct words in a file using an array list
    private static ArrayList countWordsWithArrayList(Scanner fileScanner) {


        System.out.println("Total number of words: " + numWords);
        System.out.println("number of distincy words: " + result.size());
        return result;
    }


    // determine distinct words in a file and frequency of each word with a Map
    private static Map countWordsWithMap(Scanner fileScanner) {


        System.out.println("Total number of words: " + numWords);
        System.out.println("number of distincy words: " + result.size());
        return result;
    }


    private static void showWords(ArrayList words, int numWordsToShow) {
        for(int i = 0; i < words.size() && i < numWordsToShow; i++)
            System.out.println(words.get(i));
    }


    private static void showWords(Map words, int numWordsToShow) {



    }


    // perform a series of experiments on files. Determine average time to
    // count words in files of various sizes
    private static void performExp() {
        String[] smallerWorks = {"smallWords.txt", "2BR02B.txt", "Alice.txt", "SherlockHolmes.txt"};;
        String[] bigFile = {"ciaFactBook2008.txt"};
        timingExpWithArrayList(smallerWorks, 50);
        timingExpWithArrayList(bigFile, 3);
        timingExpWithMap(smallerWorks, 50);
        timingExpWithMap(bigFile, 3);
    }


    // pre: titles != null, elements of titles refer to files in the
    // same path as this program, numExp >= 0
    // read words from files and print average time to cound words.
    private static void timingExpWithMap(String[] titles, int numExp) {
        try {
            double[] times = new double[titles.length];
            final int NUM_EXP = 50;
            for(int i = 0; i < NUM_EXP; i++) {
                for(int j = 0; j < titles.length; j++) {
                    Scanner fileScanner = new Scanner(new File(titles[j]));
                    Stopwatch st = new Stopwatch();
                    st.start();
                    Map words = countWordsWithMap(fileScanner);
                    st.stop();
                    System.out.println(words.size());
                    times[j] += st.time();
                    fileScanner.close();
                }
            }
            for(double a : times)
                System.out.println(a / NUM_EXP);
        }
        catch(FileNotFoundException e) {
            System.out.println("Problem reading the data file. Exiting the program." + e);
        }
    }


    // pre: titles != null, elements of titles refer to files in the
    // same path as this program, numExp >= 0
    // read words from files and print average time to cound words.
    private static void timingExpWithArrayList(String[] titles, int numExp) {
        try {
            double[] times = new double[titles.length];
            for(int i = 0; i < numExp; i++) {
                for(int j = 0; j < titles.length; j++) {
                    Scanner fileScanner = new Scanner(new File(titles[j]));
                    Stopwatch st = new Stopwatch();
                    st.start();
                    ArrayList words = countWordsWithArrayList(fileScanner);
                    st.stop();
                    times[j] += st.time();
                    fileScanner.close();
                }
            }
            for(int i = 0; i < titles.length; i++)
                System.out.println("Average time for " + titles[i] + ": " + (times[i] / numExp));
        }
        catch(FileNotFoundException e) {
            System.out.println("Problem reading the data file. Exiting the program." + e);
        }
    }


    // try to set look and feel to same as system
    private static void setLookAndFeel() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch(Exception e) {
            System.out.println("Unable to set look at feel to local settings. " +
            "Continuing with default Java look and feel.");
        }
    }


    /** Method to choose a file using a window.
     * @return the file chosen by the user. Returns null if no file picked.
     */
    private static File getFile() {
        // create a GUI window to pick the text to evaluate
        JFileChooser chooser = new JFileChooser(".");
        chooser.setDialogTitle("Select File To Count Words:");
        int retval = chooser.showOpenDialog(null);
        File f =null;
        chooser.grabFocus();
        if (retval == JFileChooser.APPROVE_OPTION)
            f = chooser.getSelectedFile();
        return f;
    }
}


SimpleWordCount

SimpleWordCount

Program demonstrating use of a map to count the frequency of words in a file.


import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class SimpleWordCounter {
    
    public static void main(String[] args) {
        try {
            File f = new File("ciaFactBook2008.txt");
            Scanner sc;
            sc = new Scanner(f);
            // sc.useDelimiter("[^a-zA-Z']+");
            Map wordCount = new TreeMap();
            while(sc.hasNext()) {
                String word = sc.next();
                if(!wordCount.containsKey(word))
                    wordCount.put(word, 1);
                else
                    wordCount.put(word, wordCount.get(word) + 1);
            }
            
            // show results
            for(String word : wordCount.keySet())
                System.out.println(word + " " + wordCount.get(word));
            System.out.println(wordCount.size());
        }
        catch(IOException e) {
            System.out.println("Unable to read from file.");
        }
    }
}




Stopwatch class

Stopwatch class

A class for measuring how long it takes for a program to run


/**
 A class to measure time elapsed.
*/

public class Stopwatch
{
    private long startTime;
    private long stopTime;

    public static final double NANOS_PER_SEC = 1000000000.0;

 /**
  start the stop watch.
 */
 public void start(){
  startTime = System.nanoTime();
 }

 /**
  stop the stop watch.
 */
 public void stop()
 { stopTime = System.nanoTime(); }

 /**
 elapsed time in seconds.
 @return the time recorded on the stopwatch in seconds
 */
 public double time()
 { return (stopTime - startTime) / NANOS_PER_SEC; }

 public String toString(){
     return "elapsed time: " + time() + " seconds.";
 }

 /**
 elapsed time in nanoseconds.
 @return the time recorded on the stopwatch in nanoseconds
 */
 public long timeInNanoseconds()
 { return (stopTime - startTime); }
}



BinaryConverter.

BinaryConverter.

A program with examples of various Java syntax that converts a base 10 int to base 2 String.


public class BinaryConverter {
    
    public static void main(String[] args){
        for(int i = -5; i < 33; i++){
            System.out.println(i + ": " + toBinary(i));
            System.out.println(i);
            //always another way
            System.out.println(i + ": " + Integer.toBinaryString(i));
        }
    }
    
    /*
     * pre: none
     * post: returns a String with base10Num in base 2
     */
    public static String toBinary(int base10Num){
        boolean isNeg = base10Num < 0;
        base10Num = Math.abs(base10Num);        
        String result = "";
        
        while(base10Num > 1){
            result = (base10Num % 2) + result;
            base10Num /= 2;
        }
        assert base10Num == 0 || base10Num == 1 : "value is not <= 1: " + base10Num;
        
        result = base10Num + result;
        assert all0sAnd1s(result);
        
        if( isNeg )
            result = "-" + result;
        return result;
    }
    
    /*
     * pre: cal != null
     * post: return true if val consists only of characters 1 and 0, false otherwise
     */
    public static boolean all0sAnd1s(String val){
        assert val != null : "Failed precondition all0sAnd1s. parameter cannot be null";
        boolean all = true;
        int i = 0;
        char c;
        
        while(all && i < val.length()){
            c = val.charAt(i);
            all = c == '0' || c == '1';
            i++;
        }
        return all;
    }
}




Sourcev :https://www.cs.utexas.edu/~scottm/cs307/javacode/codeSamples/BinaryConverter.java
How do I generate random string?

How do I generate random string?

package org.kodejava.example.security;

import java.security.SecureRandom;
import java.util.Random;

public class RandomString {
    public static final String SOURCES =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

    public static void main(String[] args) {
        RandomString rs = new RandomString();
        System.out.println(rs.generateString(new Random(), SOURCES, 10));
        System.out.println(rs.generateString(new Random(), SOURCES, 10));
        System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));
        System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));
    }

    /**
     * Generate a random string.
     *
     * @param random the random number generator.
     * @param characters the characters for generating string.
     * @param length the length of the generated string.
     * @return
     */
    public String generateString(Random random, String characters, int length) {
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = characters.charAt(random.nextInt(characters.length()));
        }
        return new String(text);
    }
}
Example string produced by the code snippets are:
uxEUFqTqS0
vr89vdF4gh
ysYF9XEHhO5FtDf
aBANhrLObZ1XLJ

Source :https://kodejava.org/how-do-i-generate-random-string/
String Example

String Example

A few brief examples of String manipulations


public class StringExample
{	public static void main(String[] args)
	{	String s1 = "Computer Science";
		int x = 307;
		String s2 = s1 + " " + x;
		String s3 = s2.substring(10,17);
		String s4 = "is fun";
		String s5 = s2 + s4;
		
		System.out.println("s1: " + s1);
		System.out.println("s2: " + s2);
		System.out.println("s3: " + s3);
		System.out.println("s4: " + s4);
		System.out.println("s5: " + s5);
		
		//showing effect of precedence
		
		x = 3;
		int y = 5;
		String s6 = x + y + "total";
		String s7 = "total " + x + y;
		String s8 = " " + x + y + "total";
		System.out.println("s6: " + s6);
		System.out.println("s7: " + s7);
		System.out.println("s8: " + s8);
	}
}





Source : https://www.cs.utexas.edu/~scottm/cs307/javacode/codeSamples/StringExample.java
For loop

For loop

A simple example of using for loops to calculate factorial. Uses the built in int data type so only good to 13!

public class Factorial
{
 public static void main(String[] args)
 { final int NUM_FACTS = 100;
  for(int i = 0; i < NUM_FACTS; i++)
   System.out.println( i + "! is " + factorial(i));
 }
 
 public static int factorial(int n)
 { int result = 1;
  for(int i = 2; i <= n; i++)
   result *= i;
  return result;
 }
}



Source : https://www.cs.utexas.edu/~scottm/cs307/javacode/codeSamples/Factorial.java
Calling Methods

Calling Methods

 A sample of how to call methods in the same class.


/* CallingMethodsInSameClass.java
 *
 * illustrates how to call static methods a class
 * from a method in the same class
 */

public class CallingMethodsInSameClass
{
 public static void main(String[] args) {
  printOne();
  printOne();
  printTwo();
 }

 public static void printOne() {
  System.out.println("Hello World");
 }

 public static void printTwo() {
  printOne();
  printOne();
 }
}





Source : https://www.cs.utexas.edu/~scottm/cs307/javacode/codeSamples/CallingMethodsInSameClass.java
Program to accept three integers and print the largest of the three.

Program to accept three integers and print the largest of the three.

// Obtaining input
        int x = Integer.parseInt(jTextField1.getText());
        int y = Integer.parseInt(jTextField2.getText());
        int z = Integer.parseInt(jTextField3.getText());

//Determining largest number
        int max = 0;
             max = x;

        if (y > max)
             max = y;
        if (z > max)
             max = z;    
//Setting output
        jLabel1.setText(""+max);  
What is wrong with the following code fragment?

What is wrong with the following code fragment?

Must Comment Fast.,.,.,.,

Switch (x)       
{                       
          case 1:   
          n1 = 10; 
          n2 = 20; 
                         
          case 2:   
          n3 = 30; 
          break;    
          n4 = 40; 
}                       





Ads by Google