accept only a single digit in java - java

I am writing a simple program that takes multiple inputs and displays the largest then second largest. My only problem is that I want the program to accept only single digits. I know this goes back to basics, but bear with me. The code I have written so far is:
import javax.swing.JOptionPane;
public class Largest
{
public static void main (String args[])
{
/*Set variables and include a while function to force the program to take
* ten numbers before proceeding to the rest of the program. */
int counter = 0;
int number = 0;
int largest = 0;
int second = 0;
while (counter < 10)
{
// Set the counter
counter++;
//Input integer, set the largest number as the first output
number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
if (number >= largest) {
largest=number;
} else if (number >= second && number <= largest) {
// Set the second largest integer as the output
second=number;
}
}
//Display the largest number, followed by the second largest number
System.out.println("Largest number input: " + largest);
System.out.println("Second largest input: " + second);
System.exit(0); //terminate the application
} //end method main
} //end class

For this type of problem, personally, I would use a DocumentFilter
It allows you to restrict the type of characters coming into the field as well as the number of characters.
public class RestrictInput {
public static void main(String[] args) {
new RestrictInput();
}
public RestrictInput() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(2);
field.setHorizontalAlignment(JTextField.RIGHT);
((AbstractDocument) field.getDocument()).setDocumentFilter(new RestrictFilter());
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new JLabel("Please enter a integer:"), gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
panel.add(field, gbc);
int result = JOptionPane.showConfirmDialog(null, panel, "Input", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println("Use entered " + field.getText());
}
}
});
}
public class RestrictFilter extends DocumentFilter {
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
if (currentText.startsWith("-") || text.equals("-") || fb.getDocument().getLength() < 1) {
String value = text.substring(0, 1);
if (value.equals("-")) {
if (currentText.startsWith("-")) {
super.remove(fb, 0, 1);
} else {
super.insertString(fb, 0, value, attr);
}
} else if (fb.getDocument().getLength() < 2 && (value.equals("-") || Character.isDigit(value.charAt(0)))) {
super.insertString(fb, offset, value, attr);
}
}
}
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
}
Check out MDP's Weblog and Text Component Features, in particular the section of Implementing a Document Filter

//Set the counter
counter++;
while (true) {
//Input integer, set the largest number as the first output
number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
if (number < 10 && number > -10) break; //If it's one digit, it's OK
JOptionPane.showMessageDialog(null, "Enter only one digit",
"Too many digits", JOptionPane.ERROR_MESSAGE);
}
What this does is start an infinite loop. If the number is only one digit, it will end the loop and continue on. Otherwise, it will start from the beginning of the loop again and ask for a valid number.

Just use a custom JOptionDialog where you restricted the JTextField to 1 char width.

Related

How to make buttons glow while iterating through array of buttons?

I would like to display how linear search works visually.
I have created and ADT class of just integers. I also have a frame with buttons on it, when I hit the fillButton, it generates an array of random integers which are displayed on an array of buttons.
When i hit the findButton it will look for the specific number entered. As i am iterating through the array, i would like to make corresponding button change color.
I had created a similar program that iterated through an array of buttons, and changed the color as it went through. I had used Thread.sleep(), and it was just the main class. This time i have two classes and i am not sure how to go about it. I dont't know how to go about making a connection between the ADT class and the GUI class. I've used EventObjects and custom EventListeners before, but that was merely to store objects. Any help pointing in the right direction is appreciated. Thank you.
This is part of the ADT class
public class ADT {
private int[] a;
private int nElems;
private int SIZE = 60;
public ADT(){
a = new int[SIZE];
nElems=0;
}
public void initialPlacement(int index, int value,int initialCount){
a[index] = value;
nElems = initialCount;
}
public int linearSearch(int searchKey){
int index = 0;
for(int i = 0; i < nElems; i++){
if(getVal(i) == searchKey){
index = i;
break;
}
else{
index = -1;
}
}
return index;
}
And here is part of the GUI class
public NumberFrame(){///CONSTRUCTOR===========================
arr = new ADT();
//CREATE COMPONENTS
for(int i = 0; i < 60; i++){
listButtons[i] = new JButton(String.valueOf("_"));
}
for(int i = 0; i < 60; i++){
listLabels[i] = new JLabel(String.valueOf("["+i+"]"));
}
for(int i = 0; i < 60; i++){
listMiniPanels[i] = new JPanel();
listMiniPanels[i].add(listLabels[i]);
listMiniPanels[i].add(listButtons[i]);
}
fillButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
boolean sort = true;
if(linearRadio.isSelected()){
System.out.println("linear is checked");
fill(!sort);//fills half the array and array of buttons with random numbers, unsorted
}else if(binaryRadio.isSelected()){
System.out.println("binary is checked");
fill(sort);//fills half the array with random numbers and sorts it
}else{
JOptionPane.showMessageDialog(null, "Please check a sorting method");
}
}
})
findButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
int index= 0;
if(numberField.getText().equals("")){
System.out.print("Arr size = " + arr.size());
JOptionPane.showMessageDialog(null, "You did not enter a number");
}else {
try {
int searchKey = Integer.parseInt(numberField.getText());
if(linearRadio.isSelected()){
index = arr.linearSearch(searchKey);
listButtons[index].setBackground(Color.GREEN);
if(index > -1)
JOptionPane.showMessageDialog(null, "Found number " +searchKey + " # index [" + index + "]");
else
JOptionPane.showMessageDialog(null, "No such number");
}else{
index = arr.binarySearch(searchKey);
if(index > -1)
JOptionPane.showMessageDialog(null, "Found number " + searchKey+ " # index [" + index + "]");
else
JOptionPane.showMessageDialog(null, "No such number!");
}
} catch (NumberFormatException nfe) {
System.out.println("Arr size = " + arr.size());
JOptionPane.showMessageDialog(null, "Not an integer, pleas try again!");
}
}
}
});
}//=======CONSTRUCTOR END=============================

Analysing word frequencies in applet

i am writing a program in applet to measure the frequencies of word lengths in a given amount of text and display these frequencies during applet. i have written the program and it debugs without error.
however the output says i have 255 words of every length in the text i input, i have been staring at this for hours with no luck, i am aware that the drawstring method lists these outputs horizontally which i will be fixing at a later time.
i am assuming the problem resides in the analyseText method.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.util.*;
public class StringAnalysis extends Applet implements MouseListener, ActionListener {
Font arielBold;
Label pr_Label;
TextField pr_txt;
int textFieldSize = 15;
Button pr_input1, pr_input2, pr_input3;
String textToAnalyse = ("Nothing has been entered.");
boolean output = false;
String testing ="";
//create array to show respective lengths of words
int [] lengthsOfWords = new int[textFieldSize];
//first we must separate strings from spaces and populate array for comparison
String [] arrayOfWords = new String[textFieldSize];
public void init() {
pr_Label = new Label("Enter the text you wish to analise: ");
add(pr_Label);
pr_txt = new TextField(textFieldSize);
add(pr_txt);
pr_input1 = new Button("Analyse");
pr_input2 = new Button("Reset");
add(pr_input1);
add(pr_input2);
pr_input1.addActionListener(this);
pr_input2.addActionListener(this);
}
public void start (){
setSize(1000, 500);
arielBold = new Font ("Ariel", Font.BOLD, 20);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == pr_input2) {
showStatus("Resseting....");
reset();
}
else if (e.getSource() == pr_input1){
showStatus("Analysing...a");
textToAnalyse = pr_txt.getText();
analyseText(textToAnalyse);
}
}
public void paint(Graphics g) {
String statsToOutput = ("There are:" + "\n" );
int counter = 1;
for (int lengths: lengthsOfWords) {
statsToOutput = statsToOutput +lengthsOfWords[0] + " words of length " + counter + "\n ";
counter ++;
}
if (output = true){
g.drawString(statsToOutput, 25, 200);
g.drawString("The text to be analysed is: " + textToAnalyse, 25, 100);
showStatus("Finished.");
}
else if (output = false){
g.setFont(arielBold);
g.drawString(textToAnalyse,50, 100);
showStatus("Finished.");
}
}
public void analyseText(String text){
///////////////////////////////////////////////////////////////////////////////////////////////////////
int position1 = 0, position2 = 0;
String newWord = "";
String currentLetter;
int pos1 = 0, pos2 = 0;
for ( pos1 = 0; pos1 <= arrayOfWords.length-1; pos1++) {
//Initializes a string object for each address in array
for (position1 = 0; position1 <= text.length()-1; position1++){
//steps through each character in text
currentLetter = Character.toString(text.charAt(position1));
if (currentLetter.matches("[A-Z][a-z][0-9]")) {
//checks if character is alphanumeric using regular expressions (regex)
newWord = newWord + currentLetter;
//if passes regex then ads character to word
}
}
if (newWord.length() > 0) {
pos1 = arrayOfWords.length;
}
arrayOfWords[pos1] = newWord;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
emptyArrayInt(lengthsOfWords);
//now compare each word with rest of array\
for ( pos2 = 0; pos2 <= arrayOfWords.length-1; pos2++) {
position2 = 0;
for (position2 = 0; position2 <= arrayOfWords.length-1; position2++){
if (arrayOfWords[pos2].length() == arrayOfWords[position2].length());
lengthsOfWords[arrayOfWords[pos2].length()] = lengthsOfWords[arrayOfWords[pos2].length()] + 1;
}
}
showStatus("finished analysing.");
output = true;
repaint();
}
public void emptyArrayInt(int[] array) {
int position = 0;
for (position = 0; position <= array.length-1; position ++)
array[position] = 0;
}
public void emptyArrayStr(String[] array) {
int position = 0;
for (position = 0; position <= array.length-1; position ++)
array[position] = "";
}
public void reset() {
pr_txt.setText("");
textToAnalyse = ("Nothing has been entered.");
emptyArrayInt(lengthsOfWords);
emptyArrayStr(arrayOfWords);
//repaint();
showStatus("Reset Successful.");
repaint();
}
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
i would appreciate any help on this please, (I'm desperate).
Let's try section of code :
private Map<String, int> freqWords = new HashMap<String, int>();
public void analyzeText(String text) {
// You can split with another type of delimiter
String regex = ....
String[] inputs = text.split(regex);
for (String s : inputs) {
if(freqWords.containtsKey(s)) {
int frequency = inputs.get(s);
frequency++;
inputs.put(s, frequency);
} else {
inputs.put(s, 1);
}
}
}
Hope that it can help you. The main point here is you should use data structure Map to store the frequency words.

nothing will output

no matter where I place the output statement, whether is it for 1 place of the array, all of the array, or even the count variable. I can't print out ANYTHING to the console. I have tried printing in the main, and in the functions. any ideas?
Edit1: I have discovered I can print inside a jswing window, but still no luck to the console, which is making error checking difficult.
Given the fact that I can still output correctly in a window, and people claim eclipse will print it out, I have deemed that the console for my ancient text editor is just incompetent, I appreciate the help
'
//=========================//
//colby moniz project 9-1 //
//Number sorter //
//=========================//
//===========================================//
//This program takes 10 integers and sorts //
//them into even, odd, and negative. //
//===========================================//
//=============//
//Import Files //
//=============//
import javax.swing.*; // DRAW DIALOG BOX CLASS
import java.awt.*; // IMPORT AWT TO CHANGE FONT AND COLORS
public class p91 {
public static void main(String[] args) {
//=================================//
//varbiles section //
//=================================//
sorter sort = new sorter(); //Creatests an instances of sorter, inside main.
int[] test = new int[10];
int inputNum;
//================================//
//Introduction windows //
//================================//
info( "This program will sort 10 intergers, \n into the catagories minimum, maximum and negitive",
"Introduction" );
//===========================//
//fill up array //
//===========================//
for(int count = 0; count < 10; count++)
{
inputNum = input("please input number " + (count + 1), "Input");
test[count] = inputNum;
}
for(int count = 0; count < 10; count++)
{
System.out.print(test[count]);
}
}
//====================================================//
//Functions //
//====================================================//
public static void info(String a, String b)
{
//================================//
//Introduction window //
//================================//
int close = JOptionPane.showConfirmDialog(null,
a, b,
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
checkCloseInt(close);
}
public static void checkCloseInt(int close)
{
//=====================================
//checks to see if user closed program
//=====================================
if ((close == JOptionPane.CLOSED_OPTION) ||
(close == JOptionPane.NO_OPTION) ||
(close == JOptionPane.CANCEL_OPTION))
System.exit(0);
}
public static int input(String a, String b)
{
//================================//
//input //
//================================//
boolean parsable;
int inputParse = 999;
String input;
do
{
input = JOptionPane.showInputDialog(null,
a, b,
JOptionPane.QUESTION_MESSAGE);
//======================//
//Check if close //
//======================//
if(input == null)
{
System.exit(0);
}
parsable = error(input);
}
while(parsable == false);
inputParse = Integer.parseInt(input);
System.out.print(inputParse);
return inputParse;
}
public static boolean error(String input)
{
//======================
//Check if parsable
//=======================
boolean parsable = true;
try
{
int inputParse = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
parsable = false;
}
if(parsable == false)
{
errorWindow("Please input a number");
}
return parsable;
}
public static void errorWindow(String a)
{
//================================//
//Introduction window //
//================================//
int close = JOptionPane.showConfirmDialog(null,
a, "Error",
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
checkCloseInt(close);
}
}
'
Use System.out.println(); this works for meĀ“.

Converting JTextField to an int array with exceptions

So I've been trying to figure this out but to no avail. I have to convert JTextField to an int array while having two exceptions, NumberFormatException, and ArrayIndexOutOfBoundsException. I was able to find a method to convert it, but it wont throw the NumberFormatException when I enter letters.
try {
int j=0;
String str = "" + numbersField.getText();
char digit[] = str.toCharArray();
for (int i=0; i<digit.length; i++) {
if (Character.isDigit(digit[i])) {
array[j]=Character.getNumericValue(digit[i]);
System.out.print(array[j] + " "); //Checking if it works
++j;
}
}
} catch (NumberFormatException e1) {
System.err.println("NumberFormatException: Array can only hold integers");
} catch (ArrayIndexOutOfBoundsException e1) {
System.err.println("ArrayIndexOutOfBoundsException: Array can only hold up to 10 elements");
}
Personally, I believe it's not throwing the NumberFormatException because it converts JTextField to char, but I could be totally wrong. Any help is appreciated.
EDIT: I only included part of the program since it's kinda lengthy in my opinion. Array is initialized way before this. The ultimate goal of this portion of the program is to have the user input a limit of 10 numbers while throwing an exception if a letter is inputted or if it exceeds 10 numbers. This is my first time using exceptions so I'm still relatively new to it, so please excuse me for any mistakes I've done.
You can check if whole text has only digits, then convert text to int and then put all digits to array.
Try an alternative:
String str = numbersField.getText();
try {
int value = Integer.parseInt(str);
int[] array = new int[str.lenght - 1];
j = array.length - 1;
while (value > 0) {
array[j] = value % 10;
value /= 10;
--j;
}
} catch (NumberFormatException ex) {
System.out.println("Enter only digits!")
}
UPD: also you need to check if value < 0 and show an error (if you don't accept minus sign) and use str.trim() before converting to int
Hmmm well maybe this could help, maybe not the most efficient but does its job:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class JTextFieldIntToArrayValidation extends JFrame {
private int[] integerArray;
private JButton button;
private JTextField tf;
public JTextFieldIntToArrayValidation() {
createAndShowUI();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JTextFieldIntToArrayValidation test = new JTextFieldIntToArrayValidation();
test.setVisible(true);
}
});
}
private void createAndShowUI() {
setTitle("Converting JTextField to an int array with exceptions");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addComponentsToPane();
addListeners();
pack();
tf.grabFocus();
}
private void addComponentsToPane() {
button = new JButton("Convert JTextfield to array");
tf = new JTextField(10);
getContentPane().add(tf, BorderLayout.EAST);
getContentPane().add(button, BorderLayout.WEST);
}
private void addListeners() {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String tmp = tf.getText();
char[] chars = tmp.toCharArray();
integerArray = new int[chars.length];
try {
if (integerArray.length > 10) {//if digits entered are greater then 10. This however only allows for single digits!!!
throw new ArrayIndexOutOfBoundsException("Array cannot be larger then 10: " + integerArray.length);
}
for (int i = 0; i < tmp.length(); i++) {
if (!Character.isLetter(chars[i])) {//if its not a letter
integerArray[i] = Integer.parseInt(chars[i] + "");//stops java handling chars as ints
} else {//its a letter
throw new NumberFormatException("Only valid integers must be entered no letters: " + chars[i]);
}
}
printArray();
} catch (NumberFormatException | ArrayIndexOutOfBoundsException ex) {
JOptionPane.showMessageDialog(getContentPane(), ex.getMessage());
}
}
});
}
private void printArray() {
for (int i : integerArray) {
System.out.println(i);
}
}
}

Counting the number of words in a text area

Hello everyone my first question on stack overflow
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
public class TI extends JFrame implements ActionListener
{
static int count=0;
String ct;
JTextField word;
JTextArea tohide;
public static void main(String arg[])
{
TI ti=new TI();
}
public TI()
{
JPanel j=new JPanel();
JLabel def=new JLabel("Enter the text to be encrypted");
word=new JTextField("",20);
tohide=new JTextArea("",5,20);
JButton jb=new JButton("COUNT");
tohide.setBorder(BorderFactory.createLoweredBevelBorder());
j.add(def);
j.add(tohide);
j.add(word);
j.add(jb);
add(j);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
jb.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String txt=tohide.getText();
StringTokenizer stk=new StringTokenizer(txt," ");
while(stk.hasMoreTokens())
{
String token=stk.nextToken();
count++;
}
ct=Integer.toString(count);;
word.setText(ct);
}
}
I want to count the number of words that are being typed in the textarea.There is a logical error.As I keep clicking the count button the word count increases.
You never reset the count to 0 before recalculating the number of words. There doesn't seem to be a need for count to be a class variable. Making that change would make this kind of mistake impossible.
Use javax.swing.text.Utilities which has
public static final int getWordStart(JTextComponent c, int offs)
public static final int getWordEnd(JTextComponent c, int offs)
Separating by spaces is not enough. The separator could be also tab, \n etc. chars
public void actionPerformed(ActionEvent ae) {
word.setText(String.valueOf(tohide.getText().split("\\s").length));
}
I am using the following code to do the task. The idea behind it is that each pair of words is separated by a space. hence using space to split seems straight forward. if words contain carriage return, then, replacing the carriage return with empty string has to be done before counting. I hope that it helps
public int WordCount(String Words){
//Initiate Result
String s = Words+" "; //Add space after the received string
String result ="";
int i = 0;
int count = s.length();
try {
for (i = 0; i <= count - 1; i++) {
if (count - i > 1) {
String tempString = s.substring(0, s.indexOf(" "));
if (s.contains(" ") && (!s.isEmpty())) {
s = s.substring(s.indexOf(" ") + 1, s.length());
//get substring between " " and lenght ;
} else {
if(!s.isEmpty()) {
//output nothing
}
}
} else {
//output nothing;
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return i;
}

Categories