How to check whether a number there in integer variable? [duplicate] - java

This question already has answers here:
checking an integer to see if it contains a zero
(7 answers)
Closed 7 years ago.
For example, we can find what we search in an array as below:
int values [] = {3, 5, 7};
for(int i = 0; i < values.length; i++)
{
if(values[i] == 3)
{
System.out.println("3 is in array.\n");
}
}
but what would happen if we search a number in integer value? Can we find what we search in that variable? I tried something with for each loop but it hasn't worked. Does Java provide this process?
int value = 151;
for(int found: value)
{
if(found == 3)
{
System.out.println("3 is in array.\n");
}
}

You could simply use String.contains():
if (Integer.toString(value).contains("3")) { ... }

I know this is not a neat way of doing it, nevertheless it is one of the ways to do it.
Steps involved:
1) Convert it to String.
2) Look for a particular character in that string using String's built in contains(CharSequence s) method
int value = 151;
//First Step:
String numberAsString = Integer.toString(value);
//Second Step:
if (numberAsString.contains('3')){
System.out.println("Found 3");
}
And remember variable value is not lost. You can use/reuse it.

Related

Decimal places don't go past 1 when I want more and if statement is not correct [duplicate]

This question already has answers here:
Java integer-double division confusion [duplicate]
(5 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
The code is supposed to double the mean and provide a score, i.e. 4.2231 is mean, but this code prints 4.0.
public Double mean(){
return Double.valueOf((sum() / sequence.length));
}
For this line, for example, 1 is the sequence.length.
It should print out "is wobbly" when sequence.length is less then 1 or when the list of numbers have no particular order, but this code makes it print out increasing. How do I make it so when sequence.length = 1, print wobbly. Or how should I improve my decreasing code to avoid that breach in the future
public boolean isIncreasing() {
int temp;
boolean flag = true;
for (int index = 0; index < sequence.length - 1; index++) {
temp = sequence[index];
if (temp > sequence[index + 1])
{
flag = false;
break;
}
}
return flag;
}
In java, in order to make a division return a double value, you need that divisor or dividend is a double, so for your case this should work:
return (Double.valueOf(sum()) / sequence.length);

Getting Error: java.lang.NullPointerException when work with Array in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
import java.util.Scanner;
public class Java3{
int sumAll = 0;
int sumFive = 0;
int sumLast = 0;
int arr[];
int n;
void arraySum(int[] arr) {
for (int i = 0; i < arr.length; ++i) {
sumAll += arr[i];
if (i == 4)
sumFive += sumAll;
if (i >= (arr.length - 5))
sumLast += arr[i];
}
System.out.println("sum all = " + sumAll
+ " sum first five " + sumFive
+ " sum last five " + sumLast);
}
public static void main(String [] args) {
Java3 obj1 = new Java3();
Scanner scan1 = new Scanner(System.in);
System.out.println("enter the number of elements");
obj1.n = scan1.nextInt();
System.out.println("enter the elements");
for (int i = 0; i < obj1.n; ++i)
obj1.arr[i] = scan1.nextInt();
obj1.arraySum(obj1.arr);
}
}
The error I get
java.lang.NullPointerException
Errors on Null pointer exception has been asked and answered several times before, but I do not understand those explanations. Can anyone please explain it in a very easy manner. This is my code, and it is showing me the error at runtime.
This code is supposed accepts the size of an integer array followed by the integer array. Then calls a function which calculates:
sum of all digits
sum of first 5 digits
sum of last 5 digits
and prints each value in the console..
Seems like you are a beginner in coding, nullPointerException occurs whenever you are trying to access the value of an object that is not defined.
In your case you did not define your array. You should have defined your array as given below before trying to add values into the array this will remove the exception.
obj1.arr = new int[obj1.n];
Doing this will define your array in your object and with obj1.n it will initialize its size. Hope you can proceed from here. Please refer the usage of new and constructors in java.
The problem was you took the length of array as input , but you did not initialize the array . Please add this one line in the code:
obj1.n = scan1.nextInt();
obj1.arr = new int[obj1.n];
You should define your arr size. until you define the arr size it is null, and there is no memory will be allocated. You can avoid this by using ArrayList instead of array or define your arr with sum big number of size and asker user to enter the number of values less than that size.
int arr[] = new int[100];
define the array size once you know the value
obj1.arr = new int[obj1.n+1];

Java= arbitrary placement of if statement gives different output? [duplicate]

This question already has an answer here:
Why doesn't following java code throw java.lang.StringIndexOutOfBoundsException when there is no element present at index 1?
(1 answer)
Closed 7 years ago.
I am goofing around in CodingBat with Java Strings warm-ups.
The prompt was:
Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).
last2("hixxhi") → 1
last2("xaxxaxaxx") → 1
last2("axxxaaxx") → 2
My first attempt was:
public int last2(String str) {
String last = str.substring(str.length()-2);
int count = 0;
if (str.length() < 2){
return 0;
}
for (int i = 0; i <str.length()-2; i++){
String sub = str.substring(i,i+2);
if (sub.equals(last)){
count++;
}
}
return count;
}
This code produced the correct output for all tests except when the input string had a length less than 2 (output = Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:3), etc.), meaning the if statement was ignored.
However, simply moving the if statement above the variable declarations in the beginning of the method made the code correctly pass all tests (even strings with length less than two):
public int last2(String str) {
if (str.length() < 2){
return 0;
}
String last = str.substring(str.length()-2);
int count = 0;
for (int i = 0; i <str.length()-2; i++){
String sub = str.substring(i,i+2);
if (sub.equals(last)){
count++;
}
}
return count;
}
I feel like the variable declarations shouldn't have any impact on the functionality of the if statement... what is keeping my first coding attempt from working?
In your first snippet String last = str.substring(str.length()-2); would throw an exception when str.length < 2, so the if statement didn't get executed at all.
In your second snippet you placed the if statement in the correct location.

Array printing weird character [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
I'm trying to create a program that removes a given character from an array and then prints out the new array and whenever I print it out I get weird results like [I#120acab
public static int[] removeVal(int[] numArray, int val)
{
int purge = 0;
int keep = 1;
int arrayVal = 0;
for (int item : numArray)
{
if(item == val)
purge = purge + 1;
else
keep = keep + 1;
}
int[] newArray = new int[keep];
for (int taco : numArray)
{
if(taco != val)
newArray[arrayVal] = taco;
arrayVal = arrayVal + 1;
}
return newArray;
}
You should use Arrays.toString to print the array. This will show the individual elements of the array.
The default toString implementation of Object class returns what you see.

Storing computed values to an array

I'm trying some online problems. I programmed how to solve the greatest palindrome product of 2 two-digit numbers. For example 91*99=9009. I managed to do it by using the recursive function but I wonder how can i do it using arrays like this one?
product[0]=9;
product[1]=0;
product[2]=0;
product[3]=9;
or if the computed product is 969;
product[0]=9;
product[1]=6;
product[2]=9;
Then I will output it starting from the last index to the first index then test if its equal to the original number.
EDIT:
My question is, how can i store the computed product to an array?
There's no reason to solve that Project Euler problem using arrays. But if you're fixated on it, then there is a simple algorithm to convert an array of digits into a number. Just do this:
int number = 0;
int number_2 = 0;
//going forwards:
for (int i = 0; i < array.length; i++)
{
number = number * 10 + array[i];
}
//going backwards:
for (int i = array.length - 1; i >= 0; i--)
{
number_2 = number_2 * 10 + array[i];
}
if (number == number_2)
{
//you have a palindrome
}
It's not the most efficient method, I know (#Nandkumar's is faster), but it's really really simple, that's what I was aiming for.
Create a new String from the integer product.
I won't writ you code, because it looks like an assignment, but I'll give you a hint.
Convert the int into a string first.
Characters in a string are very much like arrays, so it'll be easy to convert the string into an array.
To convert the number into an array you can try this...
Char [] product = String.valueOf("969").toCharArray();
Provide your product to String.valueOf(int), it will be converted to string and then convert it into array using String.toCharArray() like
boolean palindrome = true;
int product = 9009; // or any calculated number
char str[] = String.valueOf(product).toCharArray();
for(int i=0,j=str.length-1; i!=j ;i++,j--) {
if(str[i] == str[j]){
continue;
} else {
palindrome = false;
break;
}
}

Categories

Resources