Searching for a specific number in a int variable - java

I'm currently "learning" JavaScript + Android Studio for school and I got a little problem for which I can't find the right answer on Google:
I want to know if an int variable has a specific number, for example, I'm looking for the number 7 now int numberOne = 25824 doesn't have a 7 inside, but int numberTwo = 12387 does have one. Is there a way to search for a specific number in int variables?
I tried converting the int into a new string variable, but somehow this doesn't work :(
Here's some code I'm working with:
public int round = 1;
public String nummerSieben = "" + round;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (round % 7 == 0 || nummerSieben.contains("7")==true) {
....
} else {
....
}
}
});
Thank you for your help!

public int round = 1;
public String nummerSieben = "" + round; // nummerSieben is now "1"
You're hard-coding the value of nummberSieben. You need presumably get some value from the view, and test that. If you get it as in int, use
Integer.toString(i).contains("7") // i is whatever number you get from your view.
If you get it as a String, then half the work is already done, and you just need
i.contains("7")
As noted above, this has nothing to do with JavaScript - both your example and my answer are in Java.

Couple of things:
Your comparison is not right, method String:contains() returns a boolean,
Module % does not assert you the number will contain 7 or one of it's multiples.
Integer.toString(value) converts easily your int to String.
Knowing this, you can do:
if (Integer.toString(round).contains("7")) {
// IT CONTAINS THE NUMBER!
} else {
// IT DOES NOT CONTAIN THE NUMBER
}

Here is perfect solution of your problem
public class Finder {
static int round = 123456789;
static String str = String.valueOf(round);
public static void main(String... args) {
if (str.contains("7")) {
System.out.println("Found");
} else {
System.out.println("Can't found...");
}
}
}
Just convert your integer to String and then try to found the specific value from that string.

You don't have to convert to string in order to search specific digit in integer.
You can use math for that purpose.
Here is the code:
private static boolean isFound(int round) {
while (round > 0) {
if (round % 10 == 7)
return true;
round /= 10;
}
return false;
}
basically what this code do is checking each last digit if it's equals to 7 if not he divides the num by 10 and remove the last digit and after checking again, it will do so until no digit left (num=0) or he will find 7.

Related

Java String to Int doesn't work

I'm trying to create a simple calculator that is automatic - no more equal sign. Here's how it should go:
1. User inputs the first number.
2. User chooses an operation "add", "subtract" etc.
3. User inputs the second number. In this stage, the program should now automatically compute the answer. For example:
user inputs "2" as the first number;
user chooses "add";
user inputs "3" (second number this time)
it should then display "5" in the result box.
if the user continues to input "2", this means the second number is now "32" instead of "3", and the result will be "34"
Here's my code:
public String int_firstnumber = "";
public String int_secondnumber = "";
public int int_result = 0;
public int int_numberone = 0;
public int int_numbertwo = 0;
public String str_operation = "";
public String str_inputdisplay = "";
public String str_indicator = "none";
public String str_focus = "first";
// BUTTON 1
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//checks the indicator
if(str_focus=="first") {
int_firstnumber = int_firstnumber +"1";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
} else {
if(str_indicator=="add"){
int_secondnumber = int_secondnumber + "1";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
int_numberone = Integer.parseInt(int_firstnumber);
int_numbertwo = Integer.parseInt(int_secondnumber);
int_result = int_numberone + int_numbertwo;
lblresult.setText(int_result);
}
}
}
});
//END OF BUTTON 1
//BUTTON ADD
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
str_indicator = "add";
str_operation = " + ";
str_focus = "second";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
}
});
This somewhat works but not completely. If I Input "1", it'll display 1 on the str_inputdisplay, I then click the + symbol or the btnadd, it then displays 1+ in the str_inputdisplay. This means that we are on the second number right? However when I input 1 again, the app just force closes.
Any ideas why this is happening? Forgive my ways of code, I just started learning Java btw. Thanks!
why are you naming your variable 'int_firstnumber' when it's a string public String int_firstnumber when all your other variables are named according to the variable type like int int_result and str_operation
your code looks a bit more complicated then it needs to be. as someone mentioned you can't add two numbers when your operator is a string i.e. string operator = "+"; it won't get treated like an operand, it will get treated for the type it is which is a string.
why not if they select "first" call a method setFirstNumber that way you can validate input and set the first number.. something like this:
public void setFirstNumber(int firstNumber){
int_numberone = firstNumber;
}
and then when "add" gets selected call a second method setSecondNumber along with an addition method
public void setSecondNumber(int secondNumber){
int_numbertwo = secondNumber;'
}
and
public int addNumbers(int firstNumber, int secondNumber){
return firstNumber + secondNumber;
}
your result will be int_result = addNumbers(int_numberOne, int_numberTwo)
this way your code is much cleaner, each function is executing one task, and if you want to add additional operations later it's easy to add a function subtract, multiply, etc
public int subtractNumbers(int firstNumber, int secondNumber){
return firstNumber - secondNumber;
}
public int multiplyNumbers(int firstNumber, int secondNumber){
return firstNumber * secondNumber;
}
hope that helps!
You should add TextWatcher to the input fields. You will get the values in callbaks there which you can use to update the view showing answer.
Two issues:
When adding two strings, addition will not happen. Change it to int, long etc when you want to do operation like:
int_firstnumber = int_firstnumber +"1";
Hopefully you are properly setting the variables str_focus and str_indicator because that is not available in the code snippet you have given.
if("first".equals(str_focus)) {
......
int_firstnumber = int_firstnumber +1;
} else {
if("add".equals(str_indicator)){
......
int_secondnumber = int_secondnumber + 1;

Storing an integer, adding to itself, and using it as a parameter in a method in java

I have a problem where I have to store an integer, if a user answers Y, from an input and then using it on a method, storing that integer and then adding it to a different input from the user. The total will be used on the same method and printed only if the user inputs N.
For instance,
Y
input =3
method(input)
Y
input = 4
method(input)
N
total = 3+4
method(input, total)
I have most of the code already, I just want to know if it is possible to get the total and use it on the method
Edit: here is the code
public static boolean walk(boolean bool, String answer) {
while(bool==true) {
if (answer.equals("Y") || answer.equals("y")) {
return bool=true;
}
else if (answer.equals("N") || answer.equals("n")) {
return bool=true;
}
}
return bool;
}
public static boolean continueWalking(boolean bool, String answer, int average) {
while(bool==true){
if (answer.equals("Y") || answer.equals("y")){
return bool=true;
}
else if(answer.equals("N") || answer.equals("n")){
System.out.println("Great exercise!");
System.out.println(average);
System.exit(0);
}
}
return bool;
}
while(bool) {
System.out.println("Do you want to start/continue walking?");
String continueWalk=input.next();
int totsteps=numberOfSteps;
continueWalking(true, continueWalk,totsteps);
System.out.println("How many steps do you want to walk in this section?");
totsteps=numberOfSteps + numberOfSteps;
int numberOfSteps = input.nextInt();
NumOfsteps(numberOfSteps,1);
}
Just a couple of syntax/formatting things to start with:
your while statement while(bool==true) can be changed to just while(bool). A while loop statement just needs to evaluate to a boolean in Java, and boolean bool is already a boolean. You can do a similar thing for your return statements, change them to return bool;
To answer your question, to update an int value in Java, use +=.
int test = 0;
test += 1;
System.out.println(test); // Prints out 1
In your code, declare totsteps outside of the while loop, and change the line int totsteps=numberOfSteps; to totsteps += numberOfSteps;

How would I get a specific number range from a textfield?

I'm currently working on a search method in school and I'm stuck in a newbie mistake.
I havent been programming for long and I tried searching the internet for solutions but couldnt find any. I would need to get a number range from 1-10 from the textfield and then put it as an int. Once I've done that I would have to send it to my search method which I am working on. Thanks in advance peeps.
String Value = txfSort.getText();
int NumberValue = Integer.valueOf(Value);
Probably you should first limit the input of textFields to nummeric values. You can help your self with question here: What is the recommended way to make a numeric TextField in JavaFX?
public class NumberTextField extends TextField
{
#Override
public void replaceText(int start, int end, String text)
{
if (validate(text))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (validate(text))
{
super.replaceSelection(text);
}
}
private boolean validate(String text)
{
return text.matches("[0-9]*");
}
}
Code by: Burkhard
Above code would automaticly check on entry if input is ok. So then you just check, if value is > 0 and < 10. If that is true you just call your method and use value of textField.
One way of doing described would be this:
int value = Integer.valueOf(txfSort.getText());
if(value > 0 && value < 10)
{
myMethod(value);
}
try that one:
textField.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9')) // for numbers only
&& (caracter != '\b')) {
e.consume();
}
if (Integer.valueOf(textField.getText() + caracter) > 10) {
e.consume(); // if on the text field the numbers are bigger
// than 10, consumes the last number typed
}
}
});

Java Program does not give the output for values of n>6, Why?

import java.util.*;
class A{
static int count=0;
static String s;
public static void main(String z[]){
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
System.out.println(noOfBouncy(n));
}
public static int noOfBouncy(int k){
int limit=(int)Math.pow(10,k);
s=new String("1");
int num=Integer.parseInt(s);
while(num<limit){
if(isIncreasing(s) || isDecreasing(s) ){
}
else{
count++;
}
num++;
s=new String(Integer.toString(Integer.parseInt(s)+1));
}
count=limit-count;
return count;
}
}
public static boolean isIncreasing(String s){
int len=s.length();
for(int i=0;i<len-1;i++){
if(s.charAt(i)>s.charAt(i+1)){
return false;
}
}
return true;
}
public static boolean isDecreasing(String s){
int len=s.length();
for(int i=0;i<len-1;i++){
if(s.charAt(i)<s.charAt(i+1)){
return false;
}
}
return true;
}
I have given the definitions to the two functions used isIncreasing() & isDecresing()
The program runs well for the value of n<7 but does not respond for values above it, Why ?
I accept the programming style is very immature,please ignore.
I've tried to execute it with n=7 and it finishes in 810ms, returning 30817.
However, I recommend to you to optimize the performance of your program by saving unnecessary object instantiation: It will be better if you maintain the counter in num, and convert it to string just once, at the beginning of the loop:
int num=1;
while (num < limit)
{
s=Integer.toString(num);
if (isIncreasing(s) || isDecreasing(s))
{
}
else
{
count++;
}
num++;
}
Like this it takes just 450ms to finish.
The program was not actually stuck but it is taking way too much time to complete its execution when value of 'n' is larger.
So now the question is, I need to optimize the code to take minimum time #Little have an optimization bit that's not enough.
Any hint would be appreciable.
To increase the performance you should avoid the conversation to String and do the check with numbers.
As it doesn't matter for the result if you start the comparison from left to right or from right to left one computational solution could be.
as pseudo code
1) compare the value of the right most digit with the digit on it's left
2) is it lower --> we found a decreasing pair
3) else check if it is bigger --> we found an increasing pair
4) else --> not a bouncy pair
5) if we found already one decreasing and one increasing pair it's bouncy number
6) divide the number by ten if it's bigger then ten repeat with step 1)
The method to check if it's a bouncy number could look like this
static boolean isBouncyNumber(int number) {
boolean increasingNumber = false;
boolean decreasingNumber = false;
int previousUnitPosition = number % 10;
int remainder = number / 10;
while (remainder > 0) {
// step 1
int currentUnitPosition = remainder % 10;
if (currentUnitPosition > previousUnitPosition) {
// step 2
decreasingNumber = true;
} else if (currentUnitPosition < previousUnitPosition) {
// step 3
increasingNumber = true;
}
// step 5
if (decreasingNumber && increasingNumber) {
return true;
}
// step 6
previousUnitPosition = currentUnitPosition;
remainder = remainder / 10;
}
return decreasingNumber && increasingNumber;
}

Returning an int value from a method java

I'm pretty new to java, but I'm trying to make a simulation of the finger game, 'Sticks', using my limited knowledge. This may not be the neatest, but if you're going to make a suggestion on me to do something, link a page explaining what that thing is, and I'll read it.
Ok, so the issue comes up basically when I call a method to decide who's turn it is and trying to return the value for the "count" up to 5, but it's not returning to main()
public static int TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return Death;
}
Death is there because I was getting an error telling me that I always need to return SOMETHING so I'm returning a static value.
Basically, the problem is getting PLH (player left hand) or PRH (player right hand) to return to main. If I'm not wrong, they should return as their initial variable name (PL, and PR) with the returned value correct? If not, what can I do to fix this?
The code is a lot larger than this, and this issue is happening throughout the whole program, so I'm showing just 1 method and assuming they're all the same issue; the methods are almost all the same.
Also, while I'm typing a question already, is nextInt() the best way to do a random number generator? When I had it as nextInt(1) it was exclusively attacking the left hand, and when I switched it to nextInt(2) now it's attacking both, but occasionally the code... "crashes" (what I mean by crashes is that it generates a number outside of what the If statements are looking for). I obviously need to to generate either a 1 or a 2 (or 0 and 1 if 0 counts).
You can change your code to
public static Integer TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return null;
}
NOTE: make sure you first check for null values where you call this function.
You are generating random number twice, this is why you can observe "strange" behvior.
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5) {
...
}
else if(botAtk.nextInt(2) == 0 && PLH <= 5) {
...
}
Try generating random only once:
Random botAtk = new Random();
boolean right = botAtk.nextInt(2) == 1; // flip coin only once
if(right && PRH <= 5) {
...
}
else if(!right && PLH <= 5) {
...
}
I know the answer will not get accepted, because there is an accepted one, but nevertheless:
I suspect that you have a wrong understanding of method parameter passing in Java.
What I read from your question and comments is that you expect this to work:
public static int psInt = 0;
static void main() {
int someNumber = 1;
int someOtherNumber = 5;
method1( someNumber, someOtherNumber );
// You expect "someNumber" to be 6 right now.
// But in fact, the value will be unchanged.
// What WILL work: psInt is 0 now
method3(); // this method will modify the static class var
// psInt is 5 now.
}
static void method1( int numParam, int someothervalue ){
numParam = numParam + someothervalue;
}
static void method2( int someNumber, int someothervalue ){
someNumber = someNumber + someothervalue; // <- same name won't work either!
}
public static void method3(){
psInt = 5;
}
But in Java method arguments are passed by value. That is: a copy!
So no matter how you name the variables and arguments, you will never have an "out" argument here.
What you can do:
In a static method, you can use and modify static class variables.
In a non-static method, you can use and modify non-static and static class variables.
You can pass a State-Object, of which you can modify field values.
You can return a value.
... there are more possibilites. These just to start with.
In your case, 4. does not make so much sense, because you wouldn't know if it is the new right or left hand value.

Categories

Resources