Tuesday, December 13, 2016

Improved version of Guessing Game

import java.util.Random;
import java.util.Scanner;

public class GuessingNumber {
public static void main(String[]args){
//Generate a random number between 1 to 20
Random generator = new Random();
//store randomly generated number into variable comNum of type int
int comNum = generator.nextInt(20)+1;
//Create an object for Scanner class. 
Scanner scan = new Scanner(System.in);
boolean gameOn = true;
//create a variable to count the number of guesses. 
int guess =1;
//store user input into the variable num
int num;
System.out.printf("I am thinking of a number between 1 and 20.\n");
System.out.printf("Can you guess it?\n");
//start the while loop 
while(gameOn){
    if(guess<=4){
    System.out.printf("Enter a number to try.\n");
    num = scan.nextInt();
    if(num==comNum){
    System.out.printf("You guessed it right on %d tries\n",guess );
    break;
    }else{
    if(num<comNum){
    System.out.printf("Your guess # is lower than the one I am thinking off.\n");
   
    }else{
    System.out.printf("Your number is greater than mine.\n");
   
    }
   
    }
    }else{
    System.out.printf("You missed all your chances.The no was %d", comNum);
    break;
    }
    guess = guess+1;
}
scan.close();
}


}



Q. How to implement a loop to keep playing the game instead of restarting the program every time?

Monday, December 12, 2016

Number Guessing Game in Java

/*Description: This program implements a famous number guessing game in programming.
* There is a serious error in this code. Spot it.
*@blankbug.
*/


import java.util.Random;
import java.util.Scanner;

public class GuessingNumber {
public static void main(String[]args){
//Generate a random number between 1 to 20
Random generator = new Random();
//store randomly generated number into variable comNum of type int
int comNum = generator.nextInt(20)+1;
//Create an object for Scanner class. 
Scanner scan = new Scanner(System.in);
boolean gameOn = true;
//create a variable to count the number of guesses. 
int guess =1;
//store user input into the variable num
int num;
System.out.printf("I am thinking of a number between 1 and 20\n");
                System.out.printf("Can you guess it?");
//start the while loop 
while(gameOn){
   
    num = scan.nextInt();
    if(num==comNum){
    System.out.printf("You guessed it right on %d tries\n",guess );
    break;
    }else{
    if(num<comNum){
    System.out.printf("Your guess # is lower than the one I am thinking off.\n");
    System.out.printf("Enter it again.\n");
    }else{
    System.out.printf("Your number is greater than mine.\n");
    System.out.printf("Try it again.");
    }
   
    }
    guess++;
if(guess>4){
System.out.printf("You missed all your chances.The no was %d", comNum);
break;
}
}
}


}

----------------------------------------------------------------------------------------------------------------------
REMEMBER: There is a serious error in this program.
HINT:  Check if.. else statement inside a while loop.

Sunday, December 11, 2016

How to read a file token to token?

/*Description: this program reads a file and displays it into tokens.This program uses Scanner
class to do the job. There is no comment and explanation. If you know how to read a file then this should be obvious. This is not a good programming habit btw. We must explain or comment on the code. 
 * @author: blankbug
 * 
*/


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class StringTokenizer{
public static void main(String[]args)throws FileNotFoundException{
Scanner scan = new Scanner(System.in);
System.out.printf("Please enter the name of the file to read.\n");
File nameOfTheFile = new File(scan.nextLine());
Scanner fileReader = new Scanner(nameOfTheFile);
String fileContent ="";
while(fileReader.hasNextLine()){
fileContent = fileReader.nextLine();
Scanner scan1 = new Scanner(fileContent);
String scan2 ="";
while(scan1.hasNext()){
scan2 = scan1.next();
System.out.println(scan2);
}//end of inner while loop
scan1.close();
}//end of outer while loop
fileReader.close();
scan.close();
}//end of the main method
}//end of the class

Wednesday, December 7, 2016

Comma separated

     
     
This code is taken from the presentation of Java One keynote. The link of which is posted below the code.


Problem: Print the name of your five friends stored in an ArrayList in upper case comma separated.


import java.util.*;
import static java.util.stream.Collectors.*;

public class ArrayListExamples {
  public static void main(String[]args){
 
  Listnames = Arrays.asList("Tom","Jerry","Jane","Jack");
 
  //print the names in uppercase, comma separated
 
System.out.println(
names.stream()
.map(String::toUpperCase)
             .collect(joining(",")));
  }
  }
 ----------------------------------------------------------------------------------------------- 





Friday, November 25, 2016

How to write a file reading program in Java.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileReader{
public static void main(String[]args) throws FileNotFoundException{
//ask user to enter a file name.
Scanner scan = new Scanner(System.in);
System.out.println("Enter a file name.");
//create a file object and pass the file name to it as a parameter
File file = new File(scan.nextLine());
Scanner fileName = new Scanner(file);
while(fileName.hasNextLine()){
String line = fileName.nextLine();
System.out.println(line);
}
fileName.close();
scan.close();
}//end of the main method

}//end of the class TokenReader

Saturday, November 19, 2016

Use VIM as your text editor.

                    

Law 1      : Open the terminal and navigate to the desired location.
law 2       : Create a file by typing vim learn_vim
law 3       : Copy and pase the entire tutorial and read.

*************************************************************************


 Lesson 1.1:  MOVING THE CURSOR


   ** To move the cursor, press the h,j,k,l keys as indicated. **
--------------------------------------------------------------------------------------------
             ^
             k              Hint:  The h key is at the left and moves left.
    < h         l >                 The l key is at the right and moves right.
             j                         The j key looks like a down arrow.
             v
-----------------------------------------------------------------------


1. Move the cursor around the screen until you are comfortable.

  2. Hold down the down key (j) until it repeats.
     Now you know how to move to the next lesson.

  3. Using the down key, move to Lesson 1.2.

NOTE: If you are ever unsure about something you typed, press to place
      you in Normal mode.  Then retype the command you wanted.

NOTE: The cursor keys should also work.  But using hjkl you will be able to
      move around much faster, once you get used to it.  Really!


*************************************************************************

  Lesson 1.2: EXITING VIM


  !! NOTE: Before executing any of the steps below, read this entire lesson!!

  1. Press the key (to make sure you are in Normal mode).

  2. Type:      :q! .
     This exits the editor, DISCARDING any changes you have made.

  3. Get back here by executing the command that got you into this tutor. That
     might be:  vimtutor

  4. If you have these steps memorized and are confident, execute steps
     1 through 3 to exit and re-enter the editor.

NOTE:  :q!   discards any changes you made.  In a few lessons you
       will learn how to save the changes to a file.

  5. Move the cursor down to Lesson 1.3.


*************************************************************************

  Lesson 1.3: TEXT EDITING - DELETION


           ** Press  x  to delete the character under the cursor. **

  1. Move the cursor to the line below marked --->.

  2. To fix the errors, move the cursor until it is on top of the
     character to be deleted.

  3. Press the  x  key to delete the unwanted character.

  4. Repeat steps 2 through 4 until the sentence is correct.

---> The ccow jumpedd ovverr thhe mooon.

  5. Now that the line is correct, go on to Lesson 1.4.

NOTE: As you go through this tutor, do not try to memorize, learn by usage.


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 Lesson 1.4: TEXT EDITING - INSERTION


                        ** Press  i  to insert text. **

  1. Move the cursor to the first line below marked --->.

  2. To make the first line the same as the second, move the cursor on top
     of the first character AFTER where the text is to be inserted.

  3. Press  i  and type in the necessary additions.

  4. As each error is fixed press to return to Normal mode.
     Repeat steps 2 through 4 to correct the sentence.

---> There is text misng this .
---> There is some text missing from this line.

  5. When you are comfortable inserting text move to lesson 1.5.


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Lesson 1.5: TEXT EDITING - APPENDING


                        ** Press  A  to append text. **

  1. Move the cursor to the first line below marked --->.
     It does not matter on what character the cursor is in that line.

  2. Press  A  and type in the necessary additions.

  3. As the text has been appended press to return to Normal mode.

  4. Move the cursor to the second line marked ---> and repeat
     steps 2 and 3 to correct this sentence.

---> There is some text missing from th
     There is some text missing from this line.
---> There is also some text miss
     There is also some text missing here.

  5. When you are comfortable appending text move to lesson 1.6.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 Lesson 1.6: EDITING A FILE

                    ** Use  :wq  to save a file and exit. **

  !! NOTE: Before executing any of the steps below, read this entire lesson!!

  1. Exit this tutor as you did in lesson 1.2:  :q!
     Or, if you have access to another terminal, do the following there.

  2. At the shell prompt type this command:  vim tutor
     'vim' is the command to start the Vim editor, 'tutor' is the name of the
     file you wish to edit.  Use a file that may be changed.

  3. Insert and delete text as you learned in the previous lessons.

  4. Save the file with changes and exit Vim with:  :wq 

  5. If you have quit vimtutor in step 1 restart the vimtutor and move down to
     the following summary.

  6. After reading the above steps and understanding them: do it.




!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Lesson 2: ENOUGH
      
     1. Open terminal and type vimtutor and hit enter.
     2. Now you will read the terminal tutorial. :))









Tuesday, April 12, 2016

How to use RadioButtons? ( in java GUI)

//In this program, we will make three radio buttons namely Bold, Italic and Normal and make the text in the textField change with the button check.





import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class SimpleAnimation extends JFrame{
private JRadioButton button1;
private JRadioButton button2;
private JRadioButton button3;
private JTextField text;
private Font boldFont;
private Font italicFont;
private Font normalFont;
private ButtonGroup group;
//create a constructor 
public SimpleAnimation(){
super("Magic");               //This class is a subclass of JFrame
setLayout(new FlowLayout());
//cretes text field and writes something
text = new JTextField("Are you learning something?.");
add(text);
//create buttons and add them to the frame
button1 = new JRadioButton("Bold");
button2 = new JRadioButton("Italic");
button3 = new JRadioButton("Normal");
add(button1);
add(button2);
add(button3);
//define font
boldFont = new Font("Serif",Font.BOLD,14);
italicFont = new Font("Serif",Font.ITALIC,14);
normalFont = new Font("Serif",Font.PLAIN,14);
//radio button group
group = new ButtonGroup();
group.add(button1);
group.add(button2);
group.add(button3);
/*add itemListener (Pay attention to ItemListener here)
  * We have created a constructor of the inner class that takes
  *Font object as parameter.Why are we doing so?         */

button1.addItemListener(new ButtonActivity(boldFont));
button2.addItemListener(new ButtonActivity(italicFont));
button3.addItemListener(new ButtonActivity(normalFont));
}
//Inner class that implements ItemListener
private class ButtonActivity implements ItemListener{
private Font font;
public ButtonActivity(Font f){
font = f;
}
public void itemStateChanged(ItemEvent e){
text.setFont(font);
}
}

}





//Diver method or main method



import javax.swing.JFrame;
import javax.swing.JPanel;

public class SimpleAnimationTest {
public static void main(String[]args){
SimpleAnimation frame = new SimpleAnimation();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 200);
frame.setVisible(true);
}

}




Output:







Simple GUI to count up/down button click

PROBLEM:  Make a counter button in java


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;

import javax.swing.*;

public class UpDownPanel implements ActionListener {
private JFrame frame;
private JButton button1;
private JButton button2;
private JLabel label;
private JPanel panel;
private JPanel panel1;
private int count =50;
public void GuiAnimation(){
frame = new JFrame();
button1 = new JButton("Up");
button2 = new JButton("Down");
panel = new JPanel();
panel1 = new JPanel();
panel.add(button1);
panel.add(button2);
panel.setBackground(Color.darkGray);
label = new JLabel("Click:"+count);
panel1.add(label);
panel1.setBackground(Color.white);
button1.addActionListener(this);
button2.addActionListener(this);
frame.getContentPane().add(panel,BorderLayout.SOUTH);
frame.getContentPane().add(panel1, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event){
if(event.getSource()==button1){
label.setText("Click:"+ ++count);
}else{
label.setText("Click:"+ --count);
}
}

}


//Main class or a driver class

public class UpDown {
public static void main(String[]args){
UpDownPanel upDown = new UpDownPanel();
upDown.GuiAnimation();
}

}




Output: