Force the user to add only Hebrew letters - java

How can I make a JTextfield accept only Hebrew letters with if statement?
I can do a long if statement with all the Hebrew letters but it will not look good.
I found out that the Unicode of Hebrew first letter is \u05D0 and last one is \u05EA.
How can I say that if the gettext is in between these 2 letters so show (meaning to check if the text entered is only a Hebrew letter), the user will add only one letter in each textfield.
Thank you in advance

Build an input validator with your validation logic, and attach it to your textField to verify input as you enter it. Steps: Combine the validation logic given by #peter-lawray with the mechanism of building an input verifier and you're good to go.

You could use a simple one-liner using a Stream
boolean valid = jTextField.getText().chars().allMatch(p -> p <= 0x05ea && p >= 0x05d0);

Putting the other answers together, this is an input validator you could use:
// adapted from mohsenmadi/Daniel Rikowski
public class HebrewVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
// method suggested by Mad Matts
return text.chars().allMatch(p -> p <= 0x05ea && p >= 0x05d0);
}
}
And then you simply need to attach it to your JTextField:
myHebrewTextField.setInputVerifier(new HebrewVerifier());

Since you are using JTextField and this class inherits getText() method which returns a String. So, this is how I will probably do it.
String name = jTextField.getText();
char[] charArray = name.toCharArray();
for (char c : charArray) {
if (!(c <= 0x05ea && c >= 0x05d0)) {
break;
//valid
}
}
This can become more efficient, if you keep the counter of elements added/removed, you only will have to check the latest entered character (in case of removal you probably won't need that but that scenario will need more coding, so I hope you will figure that out once you solves this issue).
Update:
This is what I have tried:
String name = "אבגa";
char[] charArray = name.toCharArray();
for (char c : charArray) {
if (c <= 0x05ea && c >= 0x05d0) {
System.out.println("Valid hebrew");
}
}
And this prints Valid hebrew three times.

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
//...
public static String readHebrewString()
{
String str="";
System.out.println("הקלד שורה");
InputStreamReader in;
try {
char[]buffer=new char[1024];
in = new InputStreamReader(System.in, "Windows-1255");
in.read(buffer);
int i=0;
while((int)buffer[i]!=10)
str+=buffer[i++];
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Demo001.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Demo001.class.getName()).log(Level.SEVERE, null, ex);
}
return str;
}

Related

Why empty lines are being printed at the when I use BufferedReader to read characters from the console and print them?

Here is my program.
// Here we use a BufferredReader to read characters from console.
package fileIO;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BRRead {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char ch;
System.out.println("Enter characters, 'q' to quit.");
do {
ch = (char)br.read();
System.out.println(ch);
} while(ch!='q');
}
}
Input 1: testq
Output:
t
e
s
t
q
Input 2: test
Output:
t
e
s
t
""
""
""
""
where "" means empty line.
My question is why 4 empty lines are printed for the case when the input characters doesn't contain letter 'q' but aren't printed when the input characters contain letter 'q'?
Complete-er answer at the bottom
Haven't run it at all to check, though it seems like it could have something to do with the use of a do-while loop instead of a while loop
This format will make sure that the character 'q' is not read before it attempts to output anything
while(ch!='q')
{
System.out.println(ch);
ch = (char)br.read();
}
And this format prints the read character before testing if it is valid
do {
ch = (char)br.read();
System.out.println(ch);
} while(ch!='q');
EDIT after some trial/error
With this version, I have used the Scanner class which is quite similar, and I am more familiar with it. It may go something like so:
Create Object(s) for reading the data BufferedReader,Scanner,etc.
Check if there is content present
Accept the data as a String and read the first character
Output if the String is is not q
Cycle the test-> read -> print -> loop, till q is entered
Scanner input = new Scanner(System.in);
System.out.println("Enter characters, 'q' to quit.");
String read = input.nextLine();
while(read.length() <= 1 && read.charAt(0) != 'q')
{
System.out.print(read);
read = input.nextLine();
}
The (almost) original method*
Eureaka!
name.read() Reads a single character --
However, this returns an int datatype which cannot be converted with the (char) mask.
name.readLine() Reads a line of text -- With this, you can simply take the character at index 0
https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html
do {
full = br.readLine();
System.out.print(full);
} while(full.length() <= 1) && full.charAt(0) != 'q');
Not sure what the best way to do it would be between a do-while and a while loop, and that may ultimately come down to use case and opinion. and you may want to make a boolean method too
// true if String matches 'q' or "quit"
public static boolean isQuit(input)
{
String lowercase = input.toLower();
char start = input.charAt(0);
return (lowercase.equals("quit")
|| (input.length() <= 1 && start == 'q'));
}

How can I prevent the user from entering the same letter in Hangman JAVA?

I am writing a hangman program and one of the requirements to a hangman game is preventing the user from entering the same letter twice.
I have written the code for that, but the problem is every time I enter a letter it says it is already entered. I need to only say it when it is entered the second time. You guys have any suggestions? I've been trying to fix this for the past few hours, I figured I could ask on here to find some help. I already looked at another Stackoverflow question regarding something similar to this but all those solutions have the same result.
In Java, how can I determine if a char array contains a particular character?
I've tried something like this but it won't work either:
boolean contains = false;
for (char c : store) {
if (c == character) {
System.out.println("Already Entered");
contains = true;
break;
}
}
if (contains) {
// loop to top
continue;
}
SECOND CLASS-
public void hangman(String word, int life) {
KeyboardReader reader = new KeyboardReader();
char[] letter = new char[word.length()];
char[] store = new char[word.length()];
String guess;
int i = 0, tries = 0, incorrect = 0, count = 1, v = 0;
while (i < word.length()) {
letter[i] = '-';
I would just use the String.contains() method:
String aString = "abc";
char aChar = 'a';
return aString.contains(aChar + "");
To keep track of guessed letters you can use a StringBuffer, appending them using a StringBuffer.append() to append new letters (maintaining state) and use the StringBuffer.toString() method to get the String representation when you need to do the comparison above.
Since Java 1.5 the class String contains the method contains(). My idea is to collect all entered letters into a string variable and using above method:
// My code line
String letterAlreadyEntered = "";
// Your code line
char character = reader.readLine().charAt(0);
// My code line
if (letterAlreadyEntered.contains("" + character) == true) {
//Put code here what ever you want to do with existing letter
} else {
letterAlreadyEntered += character;
}
In my opinion, this is an easier way to check for occurrences than in arrays, where you have to write your own check method.

Removing special character without using Java Matcher and Pattern API

I am trying to write one java program. This program take a string from the user as an input and display the output by removing the special characters in it. And display the each strings in new line
Let's say I have this string Abc#xyz,2016!horrible_just?kidding after reading this string my program should display the output by removing the special characters like
Abc
xyz
2016
horrible
just
kidding
Now I know there are already API available like Matcher and Patterns API in java to do this. But I don't want to use the API since I am a beginner to java so I am just trying to crack the code bit by bit.
This is what I have tried so far. What I have done here is I am taking the string from the user and stored the special characters in an array and doing the comparison till it get the special character. And also storing the new character in StringBuilder class.
Here is my code
import java.util.*;
class StringTokens{
public void display(String string){
StringBuilder stringToken = new StringBuilder();
stringToken.setLength(0);
char[] str = {' ','!',',','?','.','_','#'};
for(int i=0;i<string.length();i++){
for(int j =0;j<str.length;j++){
if((int)string.charAt(i)!=(int)str[j]){
stringToken.append(str[j]);
}
else {
System.out.println(stringToken.toString());
stringToken.setLength(0);
}
}
}
}
public static void main(String[] args){
if(args.length!=1)
System.out.println("Enter only one line string");
else{
StringTokens st = new StringTokens();
st.display(args[0]);
}
}
}
When I run this code I am only getting the special characters, I am not getting the each strings in new line.
One easy way - use a set to hold all invalid characters:
Set<Character> invalidChars = new HashSet<>(Arrays.asList('$', ...));
Then your check boils down to:
if(invaidChars.contains(string.charAt(i)) {
... invalid char
} else {
valid char
}
But of course, that still means: you are re-inventing the wheel. And one does only re-invent the wheel, if one has very good reasons to. One valid reason would be: your assignment is to implement your own solution.
But otherwise: just read about replaceAll. That method does exactly what your current code; and my solution would be doing. But in a straight forward way; that every good java programmer will be able to understand!
So, to match your question: yes, you can implement this yourself. But the next step is to figure the "canonical" solution to the problem. When you learn Java, then you also have to focus on learning how to do things "like everybody else", with least amount of code to solve the problem. That is one of the core beauties of Java: for 99% of all problems, there is already a straight-forward, high-performance, everybody-will-understand solution out there; most often directly in the Java standard libraries themselves! And knowing Java means to know and understand those solutions.
Every C coder can put down 150 lines of low-level array iterating code in Java, too. The true virtue is to know the ways of doing the same thing with 5 or 10 lines!
I can't comment because I don't have the reputation required. Currently you are appending str[j] which represents special character. Instead you should be appending string.charAt(i). Hope that helps.
stringToken.append(str[j]);
should be
stringToken.append(string.charAt(i));
Here is corrected version of your code, but there are better solutions for this problem.
public class StringTokens {
static String specialChars = new String(new char[]{' ', '!', ',', '?', '.', '_', '#'});
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Enter only one line string");
} else {
display(args[0]);
}
}
public static void display(String string) {
StringBuilder stringToken = new StringBuilder();
stringToken.setLength(0);
for(char c : string.toCharArray()) {
if(!specialChars.contains(String.valueOf(c))) {
stringToken.append(c);
} else {
stringToken.append('\n');
}
}
System.out.println(stringToken);
}
}
public static void main(String[] args) {
String a=",!?#_."; //Add other special characters too
String test="Abc#xyz,2016!horrible_just?kidding"; //Make this as user input
for(char c : test.toCharArray()){
if(a.contains(c+""))
{
System.out.println(); //to avoid printing the special character and to print newline
}
else{
System.out.print(c);
}
}
}
you can run a simple loop and check ascii value of each character. If its something other than A-Z and a-z print newline skip the character and move on. Time complexity will be O(n) + no extra classes used.
String str = "Abc#xyz,2016!horrible_just?kidding";
char charArray[] = str.toCharArray();
boolean flag=true;;
for (int i = 0; i < charArray.length; i++) {
int temp2 = (int) charArray[i];
if (temp2 >= (int) 'A' && temp2 <= (int) 'Z') {
System.out.print(charArray[i]);
flag=true;
} else if (temp2 >= (int) 'a' && temp2 <= (int) 'z') {
System.out.print(charArray[i]);
flag=true;
} else {
if(flag){
System.out.println("");
flag=false;
}
}
}

Java JPasswordField

So I have to write a program that prompts the user to enter a password that has to follow three requirements: at least 8 characters long, only letters and digits, and at least two digits. Now the method I created to check these three requirements I believe is sound, but my program also has to do some exception handling and be able to ask the user to reenter the password if one of the requirements is off and display the respective error message to go along with each requirement. I created a string errorMessage to relay that message but it gives me an error when i try to call it in my main ?
My other issue is that the password must be taken in to my program by using JPasswordField but I am struggling with even setting it up because of the numerous other factors like the JPanel, buttons, and action events that I read has to go along with it. I attempted to use JPasswordField and noticed that the line that takes in the password, takes it in as an array, when my checkPassword method needs a string, how can i take in that password as a string instead?
This is what I have for my program so far:
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javafx.event.ActionEvent;
public class Ed10Chp6Ex6Point18CheckPasswordProgram {
public static void main(String[] args) {
final JFrame frame = new JFrame("Check Password Program");
JLabel jlbPassword = new JLabel("Please enter the password: ");
JPasswordField jpwName = new JPasswordField(15);
jpwName.setEchoChar('*');
jpwName.addActionListener(new ActionListener()) {
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField) e.getSource();
char[] password = input.getPassword();
if(checkPassword(password)){
JOptionPane.showMessageDialog(frame, "Congradulations, your password follows all the requirements");
}
else{
JOptionPane.showMessageDialog(frame, errorMessage);
}
}
}
}
public static boolean checkPassword(String x) {
String errorMessage = "";
//must have at least eight characters
if (x.length() < 8){
errorMessage = "The password you entered is invalid, password must be at least 8 characters";
return false;
}
//consists of only letters and digits
for (int i = 0; i < x.length(); i++) {
if (!Character.isLetter(x.charAt(i)) && !Character.isDigit(x.charAt(i))) {
errorMessage = "The password you entered is invalid, password must contain only letters and digits";
return false;
}
}
//must contain at least two digits
int count = 0;
for (int i = 0; i < x.length(); i++) {
if (Character.isDigit(x.charAt(i))){
count++;
}
}
if (count >= 2){
return true;
}
else {
errorMessage = "The password you entered is invalid, password must contain at least two digits";
return false;
}
}
}
I apologize in advanced in case some of my questions seem rudimentary, any help would be greatly appreciated, thank you!
Two things right off the bat:
(1) Make sure you are importing the correct classes, don't rely on an IDE to do proper imports. You are importing the ActionEvent class from JavaFX, but the framework you are working with is Swing.
Change
import javafx.event.ActionEvent;
To
import java.awt.event.ActionEvent;
I am not very familiar with how nicely JavaFX and Swing play with one another, but using the correct classes typically helps avoid headaches and compile/runtime errors.
(2) A static method in the java.lang.String class provides a convenient way to convert a char array into a string. In your actionPerformed method, add this:
String passStr = String.valueOf(password);
E.g.
#Override
public void actionPerformed(ActionEvent e) {
// Get the source of the event, we know it is a JPasswordField so we cast it.
JPasswordField input = (JPasswordField) e.getSource();
// Get the char array from the input the user typed stored in the input object.
char[] password = input.getPassword();
// Convert char[] to String
String passwordStr = String.valueOf(password);
if(checkPassword(passwordStr)){
JOptionPane.showMessageDialog(frame, "Congradulations, your password follows all the requirements");
} else {
JOptionPane.showMessageDialog(frame, errorMessage);
}
}
how can i take in that password as a string instead
Either checkPassword(new String(input.getPassword)) or update your method to accept a char[] instead of a String.
As for error checking, you should use throw new ShortPasswordException(), where you want to throw that error, after you implement a class like ShortPasswordException extends Exception, for example.
Then, you can do
try {
checkPassword();
} catch (ShortPasswordException e) {
// TODO: Handle exception
}
Tip for the more adventurous: Use a regular expression to check your password requirements. A match of \d{2}, for example, means you have 2 consecutive digits.

How to find how many times a letter comes up in a txt file? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
im creating a program called "Book" for school and im having alot of trouble. IM suppost to find out how many times the character "a" comes up in a txt file. The txt file reads the following "go to the bathroom
he said
and he was right
I needed to go to the bathroom" . Here is my code but it doesnt seem to work at all and i am stuck.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Book
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner text = new Scanner (new File("data.txt"));
String word = null;
int count = 0;
while(text.hasNextLine())
{
word = text.nextLine();
for (int i = 0; i < word.length(); i++)
{
if (word.substring(i) == "a")
{
count++;
}
}
}
System.out.print(count);
}
}
The substring with one parameter returns a substring that starts at the given index. Also, you do not generally compare strings in Java using ==.
You need single quotes around a to make it a character constant, and charAt to get the specific character of the string, like this:
if (word.charAt(i) == 'a')
I think you are looking the charAt() function. substring() returns a String, but you really want a Character. Note: Characters are denoted with single quotes '
if (word.charAt(i) == 'a')
word.substring(i) returns a String, when used in an equality check with ==, the String objects in the operand are compared based on their location in memory, rather than their values.
Additionally, word.substring(i) will return the entire string beginning at i, not the character at i. To return just the character, you'll need to also specify the end index. (see the docs)
This will probably work if you replace
if (word.substring(i) == "a")
with
if (word.substring(i, i+1).equals("a"))
You are reading your text file line by line but
You can use FileInputStream to read char from file.
Here is an example given.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
File file = new File("data.txt");
if (!file.exists()) {
System.out.println(args[0] + " does not exist.");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
char current;
int count = 0;
while (fis.available() > 0) {
current = (char) fis.read();
if (current == 'a') {
count++;
}
}
System.out.println(count);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here you can iterate each char of file instead of line.
Hope this will help you.

Categories

Resources