Im trying to create a EditText with a bunch of user input and add bullet per item.
The expected output look like this
• Item 1 Item 1
Item 1 also
• Item 2
• Item 3
So far I have this code below for creating a bullet when new line is occur
CustomEditText.java
...
myEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
if (text.length() == 0) {
isTyping = false;
return;
}
String newText = text.toString().replace("\n\n","\n");
if(newText.charAt(0) == '\n') {
newText = newText.substring(1);
}
if(!text.toString().equals(newText)) {
setText(newText);
myEditText.setSelection(myEditText.getText().length());
}
isTyping = true;
}
#Override
public void beforeTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
}
#Override
public void afterTextChanged(Editable editable) {
}
});
...
#Override
protected void onDraw(Canvas canvas) {
if (isTyping) {
int baseline = getBaseline();
for (int i = 0; i < getLineCount(); i++) {
canvas.drawText(" •", rect.left, baseline, paint);
baseline += getLineHeight();
}
}
super.onDraw(canvas);
}
The problem is when user input a long text (in my case I ask user for a list of procedures) it generate a bullet per line because "\n" is occured.
This is code give me output like this
• Item 1 Item 1
• Item 1 also
• Item 2
• Item 3
Is it possible in android when user pressed new line in keyboard? So I can use this to validate when user press new line or not.
I want let the user can only input 3 digit。
I try to use [0,9]{0,3} to make sure the input can not be more than 3 digit, however, the [0,9] part work, i can not input sth like abcd, but the {0,3}part doesn't work, i can input more than 3 number such as 123456
TextField textArea1 = new TextField();
textArea1.setTextFormatter(new TextFormatter<String>(new UnaryOperator<TextFormatter.Change>() {
#Override
public TextFormatter.Change apply(TextFormatter.Change change) {
String value = change.getText();
if(value.matches("[0-9]{0,3}"))
{
return change;
}
return null;
}
}));
Return the change if the change is zero or more digits and the control's text length is less than or equal to 3.
TextField textArea1 = new TextField();
UnaryOperator<Change> integerFilter = change -> {
System.out.println(change);
if (change.getText().matches("\\d*") && change.getControlNewText().length() <= 3) {
return change;
}
return null;
};
If you want to use Matches only, you need to use getControlNewText().
TextField textArea1 = new TextField();
UnaryOperator<Change> integerFilter = change -> {
System.out.println(change);
if (change.getControlNewText().matches("[0-9]{0,3}")) {
return change;
}
return null;
};
I need to create a lottery program that will allow user to select 4 numbers (image of the buttons here)
which then should be inputed into an array, I cannot get the array to fill fully, I have tried different versions of adding an int into array and I just can't seem to find the right one..
int hold;
int userNumbers[] = new int[3];
public lotteryGUI() {
initComponents();
}
private void twentyoneActionPerformed(java.awt.event.ActionEvent evt) {
hold = 21;
hold += userNumbers[0];
}
private void nineActionPerformed(java.awt.event.ActionEvent evt) {
hold = 9;
userNumbers[0]= hold + userNumbers[0];
}
private void oneActionPerformed(java.awt.event.ActionEvent evt) {
hold = 1;
userNumbers[0] = userNumbers[0] + hold ;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(Arrays.toString(userNumbers));
}
This is just a sample with 3 buttons, As you can probably tell the output i get is (10,0,0).
#edit
I have contacted my lecturer about this project and I received a little hint. I am supposed to add ActionListener and if the button is checked I am supposed to add it to an array. Not really sure how to do that, I'm going to look at some tutorials and edit this post if necessary
I would hate to hard code it, but it is really up to you to figure out how to do that for 28 buttons. Here is example for 1 button:
int counter = 0;
int[] userNumbers = new int[3];
public lotteryGUI() {
initComponents();
JButton number1 = new JButton("1");
JButton number2 = new JButton("2");
number1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userNumbers[counter] = 1;
counter = counter + 1;
if (counter == 3)
// disable all buttons and display result maybe?
}
}
// ... the rest 27 buttons maybe?
}
I am trying to create a calculator in Java.
here is all my code:
import java.util.Scanner;
public class Calculator {
public static void main (String[] args) throws java.lang.Exception{
Calculator.Calculating();
}
public static void Calculating() {
String usersCalc;
Scanner userInput = new Scanner( System.in );
System.out.println("Enter your calculation: ");
usersCalc = userInput.next();
//splits when sees plus
String[] parts = usersCalc.split("+");
//everything left to splitter
String part1 = parts[0];
//everything right to splitter
String part2 = parts[1];
int result;
int answerOne = Integer.parseInt(part1);
int answerTwo = Integer.parseInt(part2);
switch (usersCalc){
case '+':
result = answerOne + answerTwo;
break;
case '-':
result = part1 - part2;
break;
case '/':
result = part1 / part2;
break;
case'*':
result = part1 * part2;
break;
}
}
}
I am trying to do it so that the user enters a string like "2+2" and then I split it on symbol and then put it through a switch statement and it calculates it for me. however the code still has errors which I can't resolve.
any ideas?
errors
Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted
Try with contains() to check if it's +, -, * or /. Then split it and calculate it.
This is a common task for java interview: "Calculate value from string expression"
Here is the algorithm (Pseudo):
Check that expression is valid
Build a thee structure with two types of nodes - math operation and number
Recursively calculate the result
because usersCalc is a String so use "+" in place of '+'
You code have many errors:
In the switch case you are not using correct data for calculation. using part1 and part2 instead of answerOne and answerTwo Integer values.
You are passing String in the switch and using char for case statements.
For division, you should check the second value is not zero. Otherwise it will throw exception at runtime..
You can use regex for splitting the input. Then find the operator and pass it to the switch-statement.
import java.util.Scanner;
public class Calculator {
public static void main (String[] args) throws java.lang.Exception{
Calculator.Calculating();
}
public static void Calculating() {
String usersCalc;
Scanner userInput = new Scanner( System.in );
System.out.println("Enter your calculation: ");
usersCalc = userInput.next();
//splits when sees plus
String[] parts = usersCalc.split("[+-/*]");
char operator = usersCalc.contains("+") ? '+' : usersCalc.contains("-") ? '-' : usersCalc.contains("*") ? '*' : '/';
//everything left to splitter
String part1 = parts[0];
//everything right to splitter
String part2 = parts[1];
int result = -1;
int answerOne = Integer.parseInt(part1);
int answerTwo = Integer.parseInt(part2);
switch (operator){
case '+':
result = answerOne + answerTwo;
break;
case '-':
result = answerOne - answerTwo;
break;
case '/':
if (answerTwo == 0) {
System.out.println("Invalid input.");
return;
}
result = answerOne / answerTwo;
break;
case'*':
result = answerOne * answerTwo;
break;
}
System.out.println(result);
}
}
split the string by checking all possible operators
String[] parts = usersCalc.split("[+,-,*,/]");
check if userCalc contains the operator and do the same like
if (usersCalc.contains("+"))
result = answerOne + answerTwo;
else if (usersCalc.contains("-"))
result = answerOne - answerTwo;
......
Your error is propably because you try to compile with a version <1.7 (guessing from your error).
To use String with switch you need at least 1.7.
That won't resolve all your problems as other answers mention it you use String in the switch and char for the cases.
Also even with the switch statement it wont work because in "usersCalc" is still the complete calculation (e.g. 2+2) and not just the "+"
public class Calc extends MouseAdapter implements ActionListener
{
JButton[] b=new JButton[28];
static JTextField tf,tf2;
JFrame jf;
static double val1=0,val2=0,result=0;
static int operator=0,plus=1,minus=1,mul=1,div=1,rem=1,no=0,sqrt=0,hit=0,dot=0,pp=0,mp=0,mulp=0,divp=0,remp=0; //mp,pp,remp,mulp,divp all the used for operator Precedence
String str[]={"MC","MR","MS","M+","M-","<-","CE","C","+/-","sqrt","7","8","9","/","%","4","5","6","*","1/x","1","2","3","-","=","0",".","+"};
public Calc(String s)
{
jf=new JFrame(s);
JPanel p=new JPanel();
p.setBackground(new Color(213, 219, 255));
jf.add(p);
JMenuBar mb=new JMenuBar();
jf.setJMenuBar(mb);
JMenu view=new JMenu("View");
mb.add(view);
JMenu edit=new JMenu("Edit");
mb.add(edit);
JMenu help=new JMenu("Help");
mb.add(help);
JMenuItem viewHelp=new JMenuItem("View Help");
help.add(viewHelp);
JMenuItem about=new JMenuItem("About Us");
help.add(about);
mb.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
mb.setCursor(new Cursor(Cursor.HAND_CURSOR));
mb.setFont(new Font("Time_New_Roaman", 0, 11));
tf=new JTextField();
tf2=new JTextField();
tf.setBackground(new Color(242, 248, 255));
tf2.setBackground(new Color(242, 248, 255));
tf2.setBounds(10,10,190,20);
tf.setBounds(10,29,190,30);
tf.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(-1, 1, 1, 1),BorderFactory.createLineBorder(new Color(153,153,153))));
tf2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(1, 1, -1, 1),BorderFactory.createLineBorder(new Color(153,153,153))));
tf.setFont(new Font("Time_New_Roaman",0,20));
tf2.setFont(new Font("Time_New_Roaman",0,14));
tf.setHorizontalAlignment(tf.RIGHT);
tf2.setHorizontalAlignment(tf2.RIGHT);
p.add(tf);
p.add(tf2);
tf2.setCaretColor(Color.WHITE);
for(int i=0,x=10,y=32,h=27,w=34;i<str.length;i++)
{
int temp=0;
if(i==24)
h=62;
if(i==25)
{
w=73;
temp=39;
}
if(i%5==0)
{
y+=35;
x=10;
}
if(str[i]=="<-")
{
str[i]=""+(char)8592;
}if(str[i]=="sqrt")
{
str[i]="\u221A";
}if(str[i]=="+/-")
{
str[i]="\u00B1";
}
b[i]=new JButton(str[i]);
b[i].setFont(new Font("Arial",0,12));
if(str[i]=="1/x")
{b[i].setFont(new Font("Lucida Calligraphy",0, 12)); }
b[i].setBounds(x,y,w,h);
b[i].setMargin(new Insets(1,4,1,4));
if(str[i]==""+(char)8592||str[i]=="=")
{
b[i].setFont(new Font("Arial",1,20));
}
p.add(b[i]);
if(str[i]=="1"||str[i]=="2"||str[i]=="3"||str[i]=="4"||str[i]=="5"||str[i]=="6"||str[i]=="7"||str[i]=="8"||str[i]=="9"||str[i]=="0"||str[i]==".")
{
b[i].setBackground(new Color(234, 245, 248));
b[i].setFont(new Font("Arial",0,15));
}
b[i].addActionListener(this);
b[i].addMouseListener(this);
x+=39+temp;
h=27;
w=34;
}
p.setLayout(null);
Toolkit t=jf.getToolkit();
Dimension screensize=t.getScreenSize();
int width = screensize.width*8/10;
int height = screensize.height*8/10;
jf.setBounds(width/2,height/4,width,height);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(215,330);
jf.setResizable(false);
jf.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b[10]||e.getSource()==b[11]||e.getSource()==b[12]||e.getSource()==b[15]||e.getSource()==b[16]||e.getSource()==b[17]||e.getSource()==b[20]||e.getSource()==b[21]||e.getSource()==b[22]||e.getSource()==b[25])
{hit=1;sqrt=1;pp=1;mp=1;mulp=1;divp=1;remp=1;}
if(e.getSource()==b[0]) //For MC Button
{}
if(e.getSource()==b[1]) //For MR Button
{}
if(e.getSource()==b[2]) //For MS Button
{}
if(e.getSource()==b[3]) //For M+ Button
{}
if(e.getSource()==b[4]) //For M- Button
{}
if(e.getSource()==b[5]) //For Backspace Button
{
no=1;
String s=tf.getText();
tf.setText("");
for(int i=0;i<s.length()-1;i++)
{tf.setText(tf.getText()+s.charAt(i));}
if(s.length()-1==0)
tf.setText("0");
}
if(e.getSource()==b[6]) //For CE Button
{
dot=0;no=1;
tf.setText("0");
}
if(e.getSource()==b[7]) //For C Button
{
tf.setText("0");
tf2.setText("");
val1=0;val2=0;hit=0;sqrt=0;plus=1;minus=1;mul=1;div=1;rem=1;dot=0;pp=0;mp=0;mulp=0;divp=0;remp=0;no=1;
tf.setFont(new Font("Time_New_Roaman",0,20));
}
if(e.getSource()==b[8]) //For +/- Button
{}
if(e.getSource()==b[9]) //For Sqrt Button
{
dot=0;no=1;
tf2.setText("");
if(sqrt==1)
{
double t;
double num=Double.parseDouble(tf.getText());
double squareRoot = num/2;
do {
t = squareRoot;
squareRoot =(t+(num/t))/2;
}while((t-squareRoot)!=0);
tf2.setText("sqrt("+num+")");
tf.setText(""+squareRoot);
}
}
if(e.getSource()==b[10]) //For 7 Button
{
if(no==1)
{ tf.setText(""); }
tf.setText(tf.getText().concat("7"));
no=0;
}
if(e.getSource()==b[11]) //For 8 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("8"));
no=0;
}
if(e.getSource()==b[12]) //For 9 Button
{if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("9"));
no=0;
}
if(e.getSource()==b[13]) //For / Button
{
no=1;dot=0;
if(div==2 && divp==1)
{
tf2.setText(tf2.getText()+tf.getText()+"/");
serve();
minus=1;plus=1;mul=1;rem=1;
}
if(div==1 && divp==1)
{
div=2;
val1=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+"/");
operator=4;
tf.setText("");
}divp=0;
}
if(e.getSource()==b[14]) //For % Button
{
no=1;dot=0;
if(rem==1 && remp==1)
{
val2=Double.parseDouble(tf.getText());
tf2.setText(tf2.getText()+tf.getText()+"%");
result=(val1*val2)/100;
tf.setText(""+result);
plus=1;mul=1;div=1;minus=1;
}
remp=0;
}
if(e.getSource()==b[15]) //For 4 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("4"));
no=0;
}
if(e.getSource()==b[16]) //For 5 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("5"));
no=0;
}
if(e.getSource()==b[17]) //For 6 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("6"));
no=0;
}
if(e.getSource()==b[18]) //For * Button
{
no=1;dot=0;
if(mul==2 && mulp==1)
{
tf2.setText(tf2.getText()+tf.getText()+"*");
serve();
minus=1;plus=1;div=1;rem=1;
}
if(mul==1 && mulp==1)
{
mul=2;
val1=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+"*");
operator=3;
tf.setText("");
}mulp=0;
}
if(e.getSource()==b[19]) //For 1/x Button
{}
if(e.getSource()==b[20]) //For 1 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("1"));
no=0;
}
if(e.getSource()==b[21]) //For 2 Button
{
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("2"));
no=0;
}
if(e.getSource()==b[22]) //For 3 Button
{
if(no==1)
tf.setText("");
tf.setText(tf.getText().concat("3"));
no=0;
}
if(e.getSource()==b[23]) //For - Button
{
no=1;dot=0;
if(minus==2 && mp==1)
{
tf2.setText(tf2.getText()+tf.getText()+"-");
serve();
plus=1;mul=1;div=1;rem=1;
}
if(minus==1 && mp==1)
{
minus=2;
val1=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+"-");
operator=2;
tf.setText("");
}mp=0;
}
if(e.getSource()==b[24]) //For = Button
{
no=1;dot=0;mp=1;mulp=1;pp=1;divp=1;remp=1;plus=1;minus=1;mul=1;div=1;rem=1;
if(hit==1)
{
val2=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+val2);
switch(operator)
{
case 1: result=val1+val2;
break;
case 2: result=val1-val2;
break;
case 3: result=val1*val2;
break;
case 4: result=val1/val2;
break;
default: result=0;
}
tf.setText(""+result);
tf2.setText("");
val1=0;
val2=0;
}
else
{tf.setText(""+result);}
}
if(e.getSource()==b[25]) //For 0 Button
{
//dot=0;
if(no==1)
{tf.setText("");}
tf.setText(tf.getText().concat("0"));
no=0;
}
if(e.getSource()==b[26]) //For dot (.) Button
{
if(no==1)
tf.setText("");
if(dot==0)
{
dot=1;
tf.setText(tf.getText().concat("."));
}
if(dot==1)
{tf.setText(tf.getText());}
no=0;
}
if(e.getSource()==b[27]) //For + Button
{
no=1;dot=0;
if(plus==2 && pp==1)
{
tf2.setText(tf2.getText()+tf.getText()+"+");
serve();
minus=1;mul=1;div=1;rem=1;
}
if(plus==1 && pp==1)
{
plus=2;
val1=Double.parseDouble(tf.getText());
tf2.setText(tf.getText()+"+");
operator=1;
tf.setText("");
}pp=0;
}
if(tf.getText()!="") // For converting Font When Text is out of range
{
int count=0,i;
String s=tf.getText();
char ch[]=s.toCharArray();
//double d=Double.parseDouble(tf.getText());
for(i=0;i<ch.length;i++)
{
//d/=10;
count++;
}
if(count>=15&&count<20)
{
tf.setFont(new Font("Time_New_Roaman",1,16));
}if(count>=20)
{
tf.setFont(new Font("Time_New_Roaman",1,14));
}
}
}
public void mouseEntered(MouseEvent me)
{
for(int i=0;i<b.length;i++)
{
if(me.getSource()==b[i])
{
b[i].setBackground(new Color(255,204,153));
}
}
}
public void mouseExited(MouseEvent me)
{
for(int i=0;i<b.length;i++)
{
if(me.getSource()==b[i])
{
b[i].setBackground(UIManager.getColor("control"));
if(me.getSource()==b[10]||me.getSource()==b[11]||me.getSource()==b[12]||me.getSource()==b[15]||me.getSource()==b[16]||me.getSource()==b[17]||me.getSource()==b[20]||me.getSource()==b[21]||me.getSource()==b[22]||me.getSource()==b[25]||me.getSource()==b[26])
{
b[i].setBackground(new Color(234, 245, 248));
}
}
}
}
void serve()
{
val2=Double.parseDouble(tf.getText());
if(operator==1)
{
result=val1+val2;
pp=0;mp=1;mulp=1;divp=1;remp=1;
}
else if(operator==2)
{
result=val1-val2;
mp=0;mulp=1;pp=1;divp=1;remp=1;
}
else if(operator==3)
{
result=val1*val2;
mulp=0;pp=1;mp=1;divp=1;remp=1;
}
else if(operator==4)
{
result=val1/val2;
mulp=1;pp=1;mp=1;divp=0;remp=1;
}
tf.setText("");
tf.setText(""+result);
val1=Double.parseDouble(tf.getText());
}
public static void main(String... args)
{
new Calc("PariGanak");
Timer time=new Timer();
time.schedule(new TimerTask(){
public void run()
{
tf.setText("0");
no=1;
}
},100);
}
}
I have a swing application that involves a Container, a JButton, a JPanel, a JTextArea and an array. The array of String objects and contains 5 elements.
I want to return all elements in the array by a method and compare each of them with the element entered by end user in the text area, after pressing a JButton.
If they are same a JOptionPane message displaying the matched element should appear. If they are different a JoptionPane should show a message saying Number Entered is not found in myArray else, a message saying please Enter something" should appear
The problem I face is that when the end user enters a valid number a JOptionPane message saying: Number Entered is not found in myArray appear many times, e.g. when entering 4, a JoptionPane message saying
Number Entered is not found in myArray appear 3 times.
How do I prevent this message if the entered element is correct?
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Array_Search extends JFrame {
String myString[] = { "1", "2", "3", "4", "5" };
public String[] get_Element() {
String str[] = new String[myString.length];
str = myString;
return str;
}
public Array_Search() {
Container pane = getContentPane();
JPanel panel = new JPanel();
final JTextField txt = new JTextField(
" ");
JButton b = new JButton("Click Me ");
panel.add(b);
panel.add(txt);
pane.add(panel);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String[] str = get_Element();
String s2 = txt.getText().trim();
if (s2 != null && s2.length() > 0)
for (int i = 0; i < str.length; i++) {
if (s2.equals(str[i].trim())) {
JOptionPane option = new JOptionPane();
option.showInputDialog("" + str[i]);
} else {
JOptionPane option = new JOptionPane();
option.showInputDialog("Number Entered is not found in myArray");
}
}
else {
JOptionPane o = new JOptionPane();
o.showInputDialog("please Enter something");
}
}
});
}
public static void main(String[] args) {
Array_Search myArray = new Array_Search();
myArray.setSize(500, 500);
myArray.setVisible(true);
}
}
Your code shows message every time when non-matching element is found.
Instead, you need to look through all of the elements and display Not found message after that.
Something like this should work:
...
if (s2 != null && s2.length() > 0) {
boolean isFound = false;
for (int i = 0; i < str.length; i++) {
if (s2.equals(str[i].trim())) {
JOptionPane option = new JOptionPane();
option.showInputDialog("" + str[i]);
isFound = true;
break;
}
}
if(!isFound) {
JOptionPane option = new JOptionPane();
option.showInputDialog("Number Entered is not found in myArray");
}
} else
...
You return an empty Array in your get_Element method.
Can be fixed like that:
public void actionPerformed(ActionEvent ae) {
String [] str = get_Element(); // replace this
String [] str = myString; // with this
or change get_Element to:
public String[] get_Element() {
return myString;
}
Note: by Java code conventions use camel case for method names. getElement instead of get_Element.