Both '==' operator and Equals/compareTo method not working - java

I am trying to accept an array of numbers and output if the the numbers entered are distinct or not. I checked the earlier questions regarding this:
1)using '==' operator doesn't give me the correct output i.e. if the enter "2,3,4" as the command line arguments (inputs), it still returns that the "numbers are not distinct". The program could be compiled and runs in this case, but doesn't give the correct output.
2) using the 'equals' and 'compareTo' methods returns an error while compiling that, "int cannot be dereferenced!" The complilation itself is not successful here.
My code is as follows:
class DistinctNoCheck
{
public static void main(String[] args)
{ int temp = 0;
int [] a = new int [10];
for(int i=0;i<args.length;i++)
{
a[i] = Integer.parseInt(args[i]);
}
for(int i=0;i<a.length;i++)
{
temp = a[i];
for(int j=0;j<a.length;j++)
{
if((a[j] == temp) && (!(i == j)))
{
System.out.println("Numbers are not distinct!");
System.exit(0);
}
}
}
System.out.println("Numbers are distinct!");
}
}

You are using a.length which is 10. You should use args.length while iterating over the array.
Replace
for(int j=0;j<a.length;j++)
with
for(int j=0;j<args.length;j++)
Same goes for loop with i variable.

Related

Check for duplication of number in ArrayList - Java

I'm currently making a sudoku program, however my current code seems to fail me. The script below should put out a print "Inconsistent sudoku puzzle" if a row contains the same number several times, but sadly it doesn't.. I've tried several different attempts but no succes.
public void checkRow() {
int count = 0;
for(int j = 0; j < list.size(); j++) {
for(int a = 1; a < 10; a++) {
for (int i=0; i < list.get(j).length(); i++) {
if(list.get(j).charAt(i) == a) {
count++;
if(count >= 2) {
System.out.println("Inconsistent sudoku puzzle");
count = 0;
}
}
}
count = 0;
}
}
}
This is the collection of all my error checks:
public void errorCheck() {
this.checkRow();
this.checkColumn();
this.checkBox();
}
Here i load it into my main. The code is a lot more elaborate, but these should be the sections involving the issue.
public static void main(String[] args) throws Exception {
Sudoku s = new Sudoku("C:\\Users\\caspe\\Downloads\\Sudoku001.sdk");
s.printBoard();
s.errorCheck();
s.getNum();
while(getNum() > 0) {
System.out.println("Next move, please (row , column , value )");
Scanner scanner = new Scanner(System.in);
int row = scanner.nextInt();
int column = scanner.nextInt() ;
int value = scanner.nextInt();
if (s.moves(row, column, value)); {
s.errorCheck();
}
s.printBoard();
}
}
The issue
You're using charAt and trying to compare the result of that to a number:
list.get(j).charAt(i) == a
However doing so you're comparing the ascii value of the character to the number.
Example:
String a = "3";
System.out.println((int) a.charAt(0)); // This prints 51
The solution
If you wanted to compare number values you'd have to do something like this:
String a = "3";
System.out.println(Character.getNumericValue(a.charAt(0))); // This prints 3
Character.getNumericValue(a.charAt(0)) returns the number value of the character.
Implementation
Implementing that into your code would look like this:
Character.getNumericValue(list.get(j).charAt(i)) == a
This line:
if(list.get(j).charAt(i) == a)
is always false because you compare a char with an int.
Replace it with
if((list.get(j).charAt(i)-'0') == a)
list.get(j).charAt(i)-'0' gives you the numeric representation of the char
the problem is:
'if(list.get(j).charAt(i) == a)'
its comparing with the "a" value on the ascii table

Output of Adding StringArrayOfNumbers does not come as expected

Given an array of integers, check whether any number has been repeated in the array. That is, whether the array has any duplicates.
Sample Input 1
anyDuplicates({1,2,3,4})
Sample Output 1
false
Sample Input 2
anyDuplicates({11,22,33,44,22)
Sample Output 2
true
MyApproach
For checking whether the elements contains duplicates or not.I took too loops and checked whether the elements contains more than or equal to 2 times repeatition.If it does,i return false.else I return true.
public boolean anyDuplicates(int[] arr) {
boolean b1=false;
int count=0;
int z[]=new int[arr.length];
for(int i=0; i<arr.length; i++)
{ count=0; //#Edit
for(int j=0; j<arr.length; j++) {
if(arr[i]==arr[j]) {
count++;
}
}
z[i]=count;
if(z[i]>=2) {
b1=true;
break;
}
}
if(b1==true)
return true;
else
return false;
}
#Edit
DRY RUN
When I dry run the code I got my Ans as I need to put count=0 after my for i loop.Thank you all for giving me your views.
Parameters Actual Output Expected Output
{24,27,30} false false
My question:Why I am not getting expected output?
Update you code likewise,
for(int i=0;i<arr.length-1;i++)
{
for(int j=i+1;j<arr.length;j++)
{
.........
if(z[i]>=1){...}
}
}
Your mistake is, you are first taking one value that is reside into
a[i], and again into j-loop start with 0, so obviously a[i=0] and a[j=0] comes into comparison, which return true , and you will get
wrong comparion as per your requirement,
My code will work like, once value pick that is store into a[i=0...n-1],
now not repeat a[j=1...n] again unless and untill it is revise into array
Two problems with your code:
You're comparing each element with itself.
You're also comparing each pair of number twice which could be reduced to once.
Here's a sample code that could achieve solutions to both these problems:
public boolean anyDuplicates(int[] arr) {
for(int i=0; i<arr.length-1; i++) {
for(int j=i+1; j<arr.length; j++)
if (arr[i]==arr[j])
return true;
}
return false;
}
in your code, change:
if ((i!=j) && (arr[i]==arr[j]))
more clean:
public boolean anyDuplicates(int[] arr)
{
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr.length;j++)
if ((i!=j) && (arr[i]==arr[j]))
return true;
}
return false;
}
faster:
use a Set to put your values, and check the length against array length
public boolean anyDuplicates(int[] arr)
{
// => Integer[]
Integer[] array_Integer = ArrayUtils.toObject(arr);
// => Set<Integer>
Set<Integer> Set_Integer= new HashSet<Integer>(Arrays.asList(array_Integer));
// => size
int sz=Set_Integer.size();
return (sz!=arr.length);
}

What am I doing Wrong here [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I made a program to search for a certain string in another string and print Word found if the condition is true or print word not found if condition is false
The logic is as follows
enter word
length of word
for searching for letter [1]
if true
then for till length of word match with string to be searched
else continue loop
But I always get word not found no matter what the input, please help me over here!!!
The code is as follows :-
import java.util.Scanner;
class Search_i_String
{
public static void main(String args[])
{
int flag=0;
Scanner Prakhar=new Scanner(System.in);
System.out.println("Enter a String");
String ori=Prakhar.nextLine();
System.out.println("Enter the String to be Searched");
String x=Prakhar.nextLine();
char a[]=new char[ori.length()];
char b[]=new char[x.length()];
for(int i=0;i<ori.length();i++)
{
a[i]=ori.charAt(i);
}
for(int i=0;i<x.length();i++)
{
b[i]=x.charAt(i);
}
for(int i=0;i<a.length;i++)
{
if (a[i]==b[0])
{
for(int j=0;j<b.length;j++)
{
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
}
}
}
}
if (flag==0)
{
System.out.println("Word Found !!!");
}
else
System.out.println("Word not Found");
}
}
P.S. : I know I can use the contains() function but I can as my professor suggests against it and could someone please correct the program I have written, because I could have scavenged off a program from the internet too if I had to, I just wanted to use my own logic
Thank You(again)
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
j++; //add this and try once
}
If you are comparing strings in Java, you have to use equals();
So, stringA.equals(stringB);
Cheers!
Let me get this straight. You're looking for b array inside of a array? "Enter the string to be searched" means that you are searching the other way around, but I'll go with the logic your code seems to follow... Here's a naive way to do it:
if (a[i]==b[0])
{
flag = 0;
for(int j=0;j<b.length;j++)
{
if(b[j] != a[i+j]) // will array index out of bounds when its not foud
{
flag++; // you should probably break out of a named loop here
}
}
if(flag == 0){/*win*/}
}
You're modifying your first search loop with variable i when you don't have to. You can just add i to j. Also, you don't need the while loop inside if i'm understanding your problem. Like others have said, functions exist to do this already. This algorithm isn't even as efficient as it could be.
I know of an algorithm where you check starting in the last character in b instead of the first character in b to begin with. Then you can use that information to move your search along faster. Without resorting to full pseudo code, anyone know what that's called?
The simple way(but not the fastest way) is use double loop to check the chars in strings one by one, pls ref to my code and comments:
public class SearchString {
public static void main(String[] args) {
String a = "1234567890";
String b = "456";
// Use toCharArray() instead of loop to get chars.
search(a.toCharArray(), b.toCharArray());
}
public static void search(char[] a, char[] b) {
if (a == null || b == null || a.length == 0 || b.length == 0) {
System.out.println("Error: Empty Input!");
return;
}
int lenA = a.length, lenB = b.length;
if (lenA < lenB) {
System.out
.println("Error: search key word is larger than source string!");
return;
}
// Begin to use double loop to search key word in source string
for (int i = 0; i < lenA; i++) {
if (lenA - i < lenB) { // If the remaining source string is shorter than key word.
// Means the key word is impossible to be found.
System.out.println("Not found!");
return;
}
// Check the char one by one.
for (int j = 0; j < lenB; j++) {
if (a[i + j] == b[j]) {
if (j == lenB - 1) { // If this char is the last one of key word, means it's found!
System.out.println("Found!");
return;
}
} else {
// If any char mismatch, then right shift 1 char in the source string and restart the search
break;
}
}
}
}
}
You can just use String.contains();
If you really want to implement a method, try this one:
public static void main(String[] args) {
// Initialize values searchedWord and original by user
String original = [get original word from user] ;
String searchedWord = [get searched for word from user];
boolean containsWord = false;
int comparePosition = 0;
for(int i = 0; i < original.length() - searchedWord.length(); i++) {
if(original.charAt(i) == searchedWord.charAt(comparePosition)) {
comparePosition += 1;
} else {
comparePosition = 0;
}
if(comparePosition == searchedWord.length()) {
containsWord = true;
break;
}
}
return containsWord? "Word found!!" : "Word not found.";
}

Deleting Duplicate Characters in a String

Hi I need to fix this code to delete characters that repeat immediately in the string. For example: If I type aaabbbcccdeeff, it has to return abcdef at the end. However on the computer in class it returns something of a, "out of range (number)", the number being dependent on how many characters I used. On my mac however it just returns a number like 3 as an output and gives no error message. I am on Eclipse.
Please help, I didn't understand what the professor said and he rarely helps. The code is (somewhat helped by professor):
package firstProgramSimple;
import java.awt.Toolkit;
import java.util.Scanner;
public class SimpleVersion {
public static void main(String[] args) {
Scanner kb = new Scanner(System. in );
System.out.println("Entre String");
String string = kb.nextLine();
//System.out.println(string);
int length = string.length();
for (int i = 1; i < length; i++) {
if (string.charAt(i) != string.charAt(i - 1)) {
System.out.print(i);
} else if (string.charAt(i) != string.charAt(i)) {
System.out.print(i);
}
}
}
}
You need to print string.charAt(i) and not i.
Also, this piece of code is unnecessary since it will always return false:
//string.charAt(i) is always equal to itself
else if ( string.charAt(i) != string.charAt( i )) {
System.out.print(i);
Since you start at i = 1, the char at index 0 will never be printed. Before the for-loop, you should add this line:
System.out.print(string.charAt(0));
You are printing your loop counter and not the value of the char at the position of the counter:
System.out.print(i);
Should be:
System.out.print(string.charAt(i));
You will get an arrayOutOfBoundsException for inputs of size < 2. You might want to add this line once you have the string initialised:
if(string == null || string.length() < 2){
System.out.println(string);
return;
}
Something like this:
public static void main(String[] args) {
Scanner kb = new Scanner(System. in );
System.out.println("Entre String");
String string = kb.nextLine();
//System.out.println(string);
int length = string.length();
if(length < 2) {
System.out.println(string);
return;
}
System.out.print(string.charAt(0));
for (int i = 1; i < length; i++) {
if (string.charAt(i) != string.charAt(i - 1)) {
System.out.print(string.charAt(i));
}
}
}
Just replace your for loop like bellow:
System.out.print(string.charAt(0));
for (int i = 1; i < length; i++) {
if (string.charAt(i) != string.charAt(i - 1)) {
System.out.print(string.charAt(i));
}
}
The idea is, print the beginning character first, then print the character at i th position, only if its different then its previous character. Simple!

java display method

Here im required to Write a method printArray that displays the contents of the array num and Display the contents of the array with each
number separated by a space. and i have to start a new line after every 20 elements.
i wrote this code but whenever i try to execute it, it shows the array without the new line
public class project2 {
public static void main(String[] args) {
int num []= new int [100];
for (int i=0;i<num.length;i++){
num[i]=-1;
num[7]=7;
}
printArray(num);
System.out.println(num);
}
public static void printArray (int array1[]){
int count =20;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (array1[x]==count){
System.out.println(" ");
count=array1[x]+count;
}
}
}
}
import java.util.Arrays;
import java.util.Random;
public class project2 {
public static void main(String[] args) {
int num[] = new int[100];
Random random = new Random();
for (int i = 0; i < num.length; i++) {
num[i] = random.nextInt(100);
}
printArray(num);
System.out.println('\n' + Arrays.toString(num));
}
public static void printArray(int array1[]) {
int count = 20;
for (int i = 0; i < array1.length; i++) {
System.out.printf("%2d ", array1[i]);
if ((i + 1) % count == 0) {
System.out.println("");
}
}
}
}
You should use the modulo (or remainder) operator (%), that suits your usage much better:
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (x>0 && (x%count)==0){
System.out.println(" ");
}
}
This way, you will get a new line every count characters, and the first line will not have it (that is why the x>0 check is there).
Also, in the original post, this line is frankly totally bad:
count=array1[x]+count;
Just what would it do? Why do you add the value stored in the array to the fixed counter? Considering this line, I advise that you should really sit back a bit, and try to think about how things work in the background... There is no magic!
Take a closer look at your if-statement:
if (array1[x]==count)
According to your array values, this will never return true
i have to start a new line after every 20 elements.
Change to following code:
if (x%20 == 0)
{
System.out.println();
}
in place of
if (array1[x]==count)
{
System.out.println(" ");
count=array1[x]+count;
}
Problem is with
if (array1[x]==count)
You are comparing count with value present in array. Instead compare it with desired count ie 20 or Use modulo operator as suggested in other answers / comments .
int count = 1;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (count == 20){ // Check if its 20th element
System.out.println(" ");
count=1; // reset count
}
count++;
}

Categories

Resources