How can one check if an integer is equal to another in a 2D array?
int[][] board = new int [3][3];
int a = board[0][0];
int b = board[0][1];
int c = board[0][2];
int d = board[1][0];
int e = board[1][1];
int f = board[1][2];
int g = board[2][0];
int h = board[2][1];
int i = board[2][2];
I am trying to compare the integer "a" from the 2D array named "int[][]board" with the other variables (b, c, d, e, f, g, h, i) to check if "a" is equal to any of them.
I attempted to solve this issue by writing out this:
if (a == (b || c || d || e || f || g || h || i))
It seems like the operation || (known as "or") cannot be used to compare integers. How can I resolve that issue?
What you could do is iterate through the 2d array and have a boolean to check if it contains the element you are comparing with you could write something as follows:
int number = a;
boolean check = false;
for(int i = 0; i < 3; i++){ // three since you have 3 rows
for(int j = 0; j < 3; j++{ // three since you have 3 columns
if(board[i][j] == number)
check = true;
}
}
after these line of codes, you can progress to do as you please with the code
if(check){
..... // your code goes here
}
However, this will be always true if you try to compare variable "a" since the first element of your array is itself. What you could do for such situtaion is as following:
int number = a;
int count = 0;
for(int i = 0; i < 3; i++){ // three since you have 3 rows
for(int j = 0; j < 3; j++{ // three since you have 3 columns
if(board[i][j] == number)
count++;
}
}
if(count > 1) {
.... // your code goes here
}
hope it helped.
Just to address your attempt, the correct syntax for that would be
if (a == b || a == c || a == d || a == e || a == f || a == g || a == h || a == i) ....
But depending on your use case, it's probably advisable to loop over the array instead.
I would solve this by writing a general function that checks if the value at a specific position in the array occurs anywhere else:
static boolean isDuplicate(int[][] arr, int row, int col)
{
for(int r=0; r<arr.length; r++)
{
for(int c=0; c<arr[r].length; c++)
{
if(arr[r][c] == arr[row][col] && (r != row || c != col))
{
return true;
}
}
}
return false;
}
You could then do something like this:
int[][] board = {{a,b,c}, {d,e,f}, {g,h,i};
boolean duplicateA = isDuplicate(board, 0, 0);
I need to be able to save the loop results to a string to be able to manipulate the user output. No arrays
I've attempted to convert to string inside the loop which does not make much sense. I can't figure another way to save the results unless I make another method. I am not allowed create arrays.
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter phone number: ");
String number = input.nextLine();
String phone ="";
for (int i = 0; i < number.length(); i++){
if (Character.isLetter(number.charAt(i)))
phone = getNumber(Character.toUpperCase(number.charAt(i)));
else
number.charAt(i);
}
System.out.println("Your number is " + phone);
}
public static int getNumber(char uppercaseLetter){
if (uppercaseLetter >= 'W' && uppercaseLetter <= 'Z')
return 9;
else if (uppercaseLetter >= 'T' && uppercaseLetter < 'W')
return 8;
else if (uppercaseLetter >= 'P' && uppercaseLetter < 'T')
return 7;
else if (uppercaseLetter >= 'M' && uppercaseLetter < 'P')
return 6;
else if (uppercaseLetter >= 'J' && uppercaseLetter < 'M')
return 5;
else if (uppercaseLetter >= 'G' && uppercaseLetter < 'J')
return 4;
else if (uppercaseLetter >= 'D' && uppercaseLetter < 'G')
return 3;
else
return 2;
}
}
should look like: ie. 352-hey-call =
"Your number is 352-439-2255"
Actually, for each char you're looking for the corresponding letter or number, but you don't use it, you need to append them together. Using += operator on String, but as it's in a loop for better performance it's recommended to use a StringBuilder
StringBuilder phone = new StringBuilder();
for (int i = 0; i < number.length(); i++){
if (Character.isLetter(number.charAt(i))){
phone.append(getNumber(Character.toUpperCase(number.charAt(i))));
}else{
phone.append(number.charAt(i));
}
}
System.out.println("Your number is " + phone.toString());
Java says my return value int is not initialized.
public static int getRow(char r)
{
int row;
if (r == 0)
row = 0;
if (r == 1)
row = 1;
if (r == 2)
row = 2;
if (r == 3)
row = 3;
if (r == 4)
row = 4;
if (r == 5)
row = 5;
if (r == 6)
row = 6;
if (r == 7)
row = 7;
if (r == 8)
row = 8;
if (r == 9)
row = 9; //end if
return row;
}
There is an error on the return row, and it says that the int row hasn't been initialized. This method is to convert the value of a char to an int so it can be placed in an array to create a grid game. When I initialize row to 0, it doesn't hit any of the if statements and keeps the value at zero. The game is a battleship game, so the values are validated to 0-9.
What if r is not in the range of 0 to 9? Then uninitialized row will be return! Thats why you are forced to initialize row.
Initialize row with a default value, or put an else block.
I'm not sure, but are you looking for Character#getNumericValue? Read more.
So you can just easily do that:
public static int getRow(char r) {
return Character.getNumericValue(r);
}
But careful
If the character does not have a numeric value, then -1 is returned. If the character has a numeric value that cannot be represented as a nonnegative integer (for example, a fractional value), then -2 is returned.
Test live.
For your code to work, initialize int row = -1; //as below
public static int getRow(char r)
{
int row = -1;
if (r == 0)
row = 0;
if (r == 1)
row = 1;
if (r == 2)
row = 2;
if (r == 3)
row = 3;
if (r == 4)
row = 4;
if (r == 5)
row = 5;
if (r == 6)
row = 6;
if (r == 7)
row = 7;
if (r == 8)
row = 8;
if (r == 9)
row = 9; //end if
return row;
}
return value as -1 will indicate that none of the values 0 to 9 were passed.
But here the parameter passed is char. So if you want to compare chars use single quotes '1'. i.e. if you want to see if the input is character 1.
public static int getRow(char r)
{
int row;
if (r == '0')
row = 0;
if (r == '1')
row = 1;
if (r == '2')
row = 2;
if (r == '3')
row = 3;
if (r == '4')
row = 4;
if (r == '5')
row = 5;
if (r == '6')
row = 6;
if (r == '7')
row = 7;
if (r == '8')
row = 8;
if (r == '9')
row = 9; //end if
return row;
}
In your code the characters being compared are character corresponding to ASCII 0 to 9.
Assuming that you want to return same int passed as a char, you can deal this without any if. Just return r - 48; or return r - '0'; as 48 is ASCII value of 0;
public static int getRow(char r)
{
return r - 48;
}
There is a possibility that none of the if statements were true.
If you add an else and set the value of row in the else block, the compiler will detect that there are no code paths that result in an uninitialized value of row and the failure will disappear.
Making the assumption that you are expecting the a character that's in the range from '0' to '9', then this code will give you the result you are trying to produce above:
public static int getRow(char r){
return r - '0';
}
You declared int row; but you did not assign any value to it.
When your r is not in ['0' - '9'], row will not have any value, because you did not assign any value to it. That is why you have to initialize row.
You can simplify your function further :
public static int getRow(char r)
{
if( r >= '0' && r <= '9')
return r - '0';
else
return -1; // or any other value according to your logic
}
The line of code int row; declares an integer variable called row. To initialize your row variable, you need to give it a value. If your character r is not between 0 and 9, your row variable will never have a value assigned to it.
You can declare and initialize your row variable in the same line, as such:
int row = 0;
However, Java has a built in method to do this conversion for you, so you don't need to write your own method to do it. Instead of creating your getRow(char r) method, you could simply call the built in method, Character.getNumericValue(char r).
First, row will not have a value if all of the if statements are false. That is the cause of your error.
Second, the "structure" of this method, IMO, is too monotonous and can be cleaned up. Let's consider -1 to be the sentinel value.
public static int getRow(char r)
{
int row = -1;
if ('0' <= r && r <= '9') {
row = r - '0';
}
return row;
}
Even shorter/cleaner with ternary operators and without a local variable:
public static int getRow(char r) {
return ('0' <= r && r <= '9') ? r - '0' : -1
}
If none of your if statements wouldn't be true then what would be the return value ? You can either initialized your "row" variable to something because local variable are not like instance variables, they need to be initialized with something because they don't have a thing called a default value.
public static int getRow(char r)
{
int row=-1;
if (r == 0)
row = 0;
if (r == 1)
row = 1;
if (r == 2)
row = 2;
if (r == 3)
row = 3;
if (r == 4)
row = 4;
if (r == 5)
row = 5;
if (r == 6)
row = 6;
if (r == 7)
row = 7;
if (r == 8)
row = 8;
if (r == 9)
row = 9; //end if
return row;
}
so once you initialize your variables like above, if none of your if statements evaluate true then it returns -1
Also use a switch statement instead of these bunch of if statements.it will be much clear and best practice.
I'm going to guess that this is because you're comparing a character to an integer value instead of a character value.
r == 3;
//is not the same as
r == '3';
EDIT:
If you want to simply fix your code, otherwise (because, it was pointed out, you lack a definitive initialization), you remove one of your cases and make it your else case.
{
int row;
if (r == 0)
row = 0;
else if (r == 1)
row = 1;
else if (r == 2)
row = 2;
else if (r == 3)
row = 3;
else if (r == 4)
row = 4;
else if (r == 5)
row = 5;
else if (r == 6)
row = 6;
else if (r == 7)
row = 7;
else if (r == 8)
row = 8;
else (r == 9)
row = 9; //end if
return row;
}
This is fundamentally the same as what is known as a "switch - case":
//char r
switch(r) {
case '0': row = 0;
break;
case '1': row = 1;
break;
case '2': row = 2;
break;
case '3': row = 3;
break;
case '4': row = 4;
break;
case '5': row = 5;
break;
case '6': row = 6;
break;
case '7': row = 7;
break;
case '8': row = 8
break;
default: row = 9;
}
return row;
Java's compiler is smart enough to find that there is at least one instance where it should have been initialized and move forward.
It can handle some more complex cases, but if... else... should always pass.
In the context of battleship, your range of inputs is '0' - '9', so you can assume that if you ever give it anything else that it's garbage input.
However, be mindful, this isn't necessarily the best solution, just the most obvious. Review the other answers here for more insight.
A big part of things you're likely to do in the future will relate to working with characters or strings and extracting data, like you are doing here.
//char r
return Integer.parseInt(r +""); //+"" converts 'r' to "r"
//or, as mentioned below
return Character.getNumericValue(r);
//works for things like roman numerals
//but also will always return SOME value.
//Be aware of this, because you may not expect to get an int for 'a'
Will either return an integer, or throw a NumberFormatException, with no further checking.
I have an assignment to create my own implementation of a class to handle integers of unlimited size, and then to compare my implementation's runtime to that of Java's BigInteger. When I measured and graphed the runtime of my add function it was a parabola, implying a big theta running time of Ө(n^2). I have no nested loops so I expected it to be Ө(n) and cannot figure out why it isn't. I suspect it might be that I use
string += integer
in my add method inside a loop. I am not quite sure how that operation is implemented, is it a runtime of Ө(n)? If not, can anyone spot why my code isn't Ө(n)?
Here is my add method and the constructor it calls.
public HugeInteger(String val) throws IllegalArgumentException{
String temp = "";
boolean leading = true;
//check valid input
for(int i=0; i<val.length(); i++){
if(val.charAt(i) < '0' || val.charAt(i) > '9') //checks if each digit is a number from 0 to 9
if(i!=0 || val.charAt(i) != '-') //doesn't throw if the digit is a '-' at the first character of string
throw new IllegalArgumentException("Input string must be a number");
}
//remove leading zeros
for(int i=0; i<val.length(); i++){
if(!leading || val.charAt(i) != '0')
temp += val.charAt(i);
if(val.charAt(i) > '0' && val.charAt(i) <= '9') //reached first non-zero digit
leading = false;
}
if(temp == "") //this happens when the input was just a string of zeros
temp = "0";
val = temp;
if(val.charAt(0) != '-'){ //no negative sign
digits = new int[val.length()];
for(int i=0; i<val.length(); i++){
digits[i] = (int)(val.charAt(val.length()-1-i) - 48); //in ASCII the char '0' == 48
}
negative = false;
}
else{
digits = new int[val.length() - 1];
for(int i=1; i<val.length(); i++){ //for loop starts after the '-' sign
digits[i-1] = (int)(val.charAt(val.length()-i) - 48); //in ASCII the char '0' == 48
}
negative = true;
}
}
public HugeInteger add(HugeInteger h){
int carry = 0;
int size = digits.length>h.digits.length?digits.length:h.digits.length; //choose larger # of digits
String sum = "";
String sumFlipped = "";
int bigger = 0;
boolean swapped = false;
int temp;
int sign = 1;
int hsign = 1;
//assign sign based on negative or not
if(negative && !h.negative)
sign = -1;
if(!negative && h.negative)
hsign = -1;
//compare magnitudes. 1 means this is biger and -1 means h is bigger
if(digits.length>h.digits.length)
bigger = 1;
else if(digits.length<h.digits.length)
bigger = -1;
else{ //same length
for(int i=0; i<digits.length; i++){ //both digits arrays are same length
if(digits[digits.length-1-i] > h.digits[h.digits.length-1-i]){
bigger = 1;
break;
}
if(digits[digits.length-1-i] < h.digits[h.digits.length-1-i]){
bigger = -1;
break;
}
}
}
//positive number must be bigger than negative number for long subtraction
//if not, swap signs
if(bigger == 1 && negative && !h.negative){ //this is bigger and negative
swapped = true;
sign *= -1;
hsign *= -1;
}
if(bigger == -1 && !negative && h.negative){ //h is bigger and negative
swapped = true;
sign *= -1;
hsign *= -1;
}
for(int i=0; i<size; i++){
if(i>=digits.length)
temp = h.digits[i]*hsign + carry;
else if(i>=h.digits.length)
temp = digits[i]*sign + carry;
else
temp = digits[i]*sign + h.digits[i]*hsign + carry;
if(temp>9){ //adds the digit to the string, then increments carry which is used in next iteration
temp -= 10;
sum += temp;
carry = 1;
}
else if(temp<0){
temp += 10;
carry = -1;
sum += temp;
}
else{
sum += temp;
carry = 0;
}
}
if(carry == 1)
sum += 1;
if(negative && h.negative || swapped)
sum += '-';
//flip string around
for(int i=0; i < sum.length(); i++){
sumFlipped += sum.charAt(sum.length() - 1 - i);
}
HugeInteger sumHugeInteger = new HugeInteger(sumFlipped);
return sumHugeInteger;
}
import java.lang.Integer;
import java.util.Arrays;
public class Decimal {
//initialize intance variables
private int decimal;
private String hex;
public static void toHex(String s) {
int decimal = Integer.parseInt(s); //converts the s string into an int for binary conversion.
String hex = null;
int[] binNum = new int[16];
int[] binNumNibble = new int[4]; //A nibble is four bits.
int nibbleTot = 0;
char hexDig = '\0';
char[] cvtdHex = new char[4];
StringBuffer result = new StringBuffer();
for(int a = 32768; a == 1; a /= 2) { //32768 is the value of the largest bit.
int b = 0;//Will top at 15 at the end of the for loop. 15 references the last spot in the binNum array.
if(decimal > a) {
decimal -= a;
binNum[b++] = 1;//Arrays have a default value of zero to all elements. This provides a parsed binary number.
}
}
for(int a = 0; a == 15; a += 3) {
//Copies pieces of the binary number to the binNumNibble array. .arraycopy is used in java 1.5 and lower.
//Arrays.copyOfRange is used in java 1.5 and higher.
System.arraycopy(binNum, a, binNumNibble, 0, 4);
for(int b = 8; b == 1; a += 3) {
int c = 0;
nibbleTot += binNumNibble[c++];
//Converts the single hex value into a hex digit.
if(nibbleTot >= 1 && nibbleTot <= 9) {
hexDig += nibbleTot;
} else if(nibbleTot == 10) {
hexDig = 'A';
} else if(nibbleTot == 11) {
hexDig = 'B';
} else if(nibbleTot == 12) {
hexDig = 'C';
} else if(nibbleTot == 13) {
hexDig = 'D';
} else if(nibbleTot == 14) {
hexDig = 'E';
} else if(nibbleTot == 15) {
hexDig = 'F';
}
cvtdHex[c++] = hexDig;
}
}
//return hex = new String(cvtdHex);
hex = new String(cvtdHex);
System.out.print("Hex: " + hex);
}
}
I can't seem to figure out why variable hex is returned as a blank variable. I've been using System.out.print(); in each for loop and none of them are used, giving me the impression that the for loops are being skipped entirely, but I don't understand why and I'm on a time limit.
Any help is much appreciated, but please don't just paste code. I need to understand this for my computer science class!
yes, your for loops ARE being skipped, since the second part of the for statement is not the break condition but the condition that has to be fullfilled for the loop to run.
So it is NOT
for(a = 0; a == 15; a += 3)
but
for(a = 0; a <= 15; a += 3)
and so on...
The for loops wont execute because of the double ==
How about
String.format("%h", 256)