int A does not equal int B [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have two integers that I want to compare. The first integer is created from a byte of utf-8 and the second integer is the one I want to check to see if it equals.
int a = 106;
int b = (int)byteArray[0]; //which actually equals 106 when you printstatement it
but....
(a==b) //always equals false
int i = 0; While(b != i) { println(i); i++;} //eventually escapes the loop and is true
Are primitives also referenced when created? And why does a never equal b unless I count all the way up to 106?
Is there a better way to compare bytes? because I've tried all forms of variables and they do not work either.

The problem is somewhere else in your code (in the part that you are not showing). This is why you are being suggested to provide an SSCCE.
The following works as expected (i.e. prints true):
public class Test
{
public static void main(String[] args) throws Exception
{
byte[] byteArray = new byte[] { 106 };
int a = 106;
int b = (int) byteArray[0];
if (a == b)
System.out.println("true");
}
}
Most probably, in your code byteArray[0] does NOT contain 106. An SSCCE would show this.

Related

Using functions in Java Programming [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have doubt in using functions in java. I have wrote code for sum of natural numbers using a recursive function but I don't understand the error I am getting. I know it's a silly question though I'm a beginner and I need a brief explanation.
Here is the code
import java.util.Scanner;
public class natural {
public static int main(String args[]){
int a, s = 0,y;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number:");
int x = in.nextInt();
public static int SN(y)
{
if(x==1)
{
return 1;
}
else{
int N = SN(x-1) + x;
return N;
System.out.println("THE SUM IS :"+x);
}
}
Several problems:
You cannot declare a method within a method. Your SN method must be declared outside of the main method.
The parameter y in your SN method must have a type. Based on usage, it is probably supposed to be an int, so the method signature should look like SN(int y).
Despite the method parameter being called y, you appear to be using x everywhere. You should change x to y in the SN method, since that is the label of the data being passed to the method.
As others have pointed out, statements after the return line are unreachable, and as Matt Coubrough said, your IDE is likely warning you about this. Place it before the return line.
Well, one problem here is that you have an unreachable statement. Your System.out.println("THE SUM IS...") is never reached.

Java, Methods? Or constructors ? I am not sure what to call it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am not sure if you see what I am trying to do here but basically I have a few questions and problems
1)The part that is called public MethodPractice() ... what is this called? is this considered a constructor a method or what?
2)The part named MethodPracticeDiff() . . . is this allowed and if so how do I insert it into the main method for execution...
Do you guys see what I am trying to do here? Basically I want to split the program up into different pieces for example let say I wanted my own space for a calculation method to add to numbers up
and another method to define the numbers like give them a value
and a last method with a for loop making the numbers printout 10times
Any who before I make this more confusing than what it is, my question is how do I make this program execute
public class MethodPractice {
public static void main (String[]args){
MethodPractice add = new MethodPractice();
//MethodPracticeDiff add2 = new MethodPracticeDiff();
}
public MethodPractice() {
int x = 0;
int y = 99 ;
int total = x + y;
System.out.println(total);
}
public void MethodPracticeDiff(){
int z = 10;
int k = 25;
int total = z + k;
System.out.println(total);
}
}
(1) If it's in class MethodPractice, it's a constructor.
(2) Yes, this is allowed. But it's a method not a constructor. Standard practice is to begin it with a lowercase letter.
As follows in the main() method:
MethodPractice add = new MethodPractice();
add.methodPracticeDiff();
MethodPractice() is a constructor -- it has no return value and matches the name of the class.
MethodPracticeDiff() is a method -- it has a return value and does not match the name of a class.
You call methods once you have an instance of the class. e.g.
MethodPractice add = new MethodPractice();
add.MethodPracticeDiff();

Comparing elements of two arrays in a for loop (java)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
It seems to be a very common question relating with arrays and comparing in java, however I couldn't find the right answer in all of these for my case.
In this application I am trying to make a program which 'encrypts' text given by the user. For example: user gives characters 'a b c' and the program returns it as '# # $'. But as you may notice I am having some issues in the code
"pozita[i] = j;".
Why won't this code work? It doesn't give me an error? Or is there anyway of doing it as "new pozita[i]" or anything like that?
Well, I'd be glad if someone could help me through. I am stuck for a while. Thanks in advance! :)
import java.util.*;
import javax.swing.*;
import java.awt.*;
public class TestPerProgram extends JFrame
{
char[] alfabeti = {'a','b','c','r','n','t'};
char[] kodimi = {'#','#','%','*','^','$'};
int[] pozita;
//Scanner merr = new Scanner(System.in);
String fn = JOptionPane.showInputDialog("Jepe tekstin:");
char[] input = fn.toCharArray();
void numro()
{
for (int i=0; i<=input.length; i++)
{
for(int j=0; j<=input.length; j++)
{
if(alfabeti[j] == input[i])
{
pozita[i] = j;
System.out.println(pozita[i]);
}
}
}
/*
for (int k=0; k<=input.length; k++)
{
System.out.println(pozita[k]);
}
*/
}
public static void main(String[] args)
{
TestPerProgram pjesa = new TestPerProgram();
pjesa.numro();
}
}
I'm not 100% clear on how your algorithm is supposed to work, but it seems you may want to replace the line
pozita[i] = j;
with
pozita[i] = kodimi[j];
Right now, you are only writing the matching index to pozita, not a replacement character.
If my assumption is correct, you would also change
int[] pozita;
to
char[] pozita;
and initialize it to an array of length input.Length.
You never instantiated the array pozita. After you instantiate pozita, you can then start overriding the values in pozita. You are assigning j to posita[i] , posita is null.
Do something like:
int posita[] = new int[20]
and if you don't want to set size then just use an arraylist.
You have not requested memory to be allocated for your variable pozita or otherwise instantiated it. The way you are currently using it, you would write pozita[] = new int[input.length]; at some point after retrieving your input from the user.

drawString in loop writes only once instead of multiple times [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What would this code do?
for(int i = 0; i < enemysno; i++){
g.drawString("\nArray size: " + i, 200, 200);
}
enemysno is a random number between 0 and 10, and works fine. Problem is, it loops once, but then stops adding new lines after the first iteration.
As Psuedo code, I though the i starts as 0. Then compares the condition, if its false, does the code, then makes the ++ iterations, then repeats the loop?
Ultimatly, I want to add n objects to an array, but I can quite get this to work simple array to work!
A simple test proves the loop indeed works as intended:
public static void main(String[] args)
{
int enemysno = 5;
for (int i = 0; i < enemysno; i++)
{
System.out.println("lalala " + i);
}
}
this works fine producing
lalala 0
lalala 1
lalala 2
lalala 3
lalala 4
It was kind of obvious, but via debugging or such a test you could determine that the loop itself is entered the desired numer of times. The problem must be in your string display: most probably your drawString method overwrites the printed string each time.
It should be obvious if you checked the numbers on your output.
The solution?
use a string builder to concatenate the partial strings and then draw the final string using your drawString method

nullPointerException in multiarray [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am making a Realm plugin for my server, and I am using a multiarray to detect the location of users portals, below is the code:
public static String[][][] realms;
#EventHandler
public void onPlayerInteract(final PlayerInteractEvent event) throws Exception {
if( event.getMaterial() == Material.NETHER_STAR ) {
int x = (int) event.getClickedBlock().getX();
int y = (int) event.getClickedBlock().getY();
int z = (int) event.getClickedBlock().getZ();
** realms[x][y][z] = event.getPlayer().getName();
createPortal();
}
}
I get a NullPointerException at the line with the '**', can someone please explain what I am doing wrong? I have googled 'java multiarrays', and they all seem to work the same way.
You are getting a null pointer exception because you haven't initialized the array.
You can initialize the array like this:
String string[][][] = new String[3][3][3];
you need to know what would be the length of the arrays, because if you try to access or save a value with an index that doesn't exists you are going to get a IndexArrayOutOfBounds exception
Array life cycle consists of three things
1. Array type declaration
2. Array initialization
3. Array utilization
But you have not declared an array rather you have just declared an variable and informed compiler that you wish to have an 3- dimensional array named "realms" of type "String" but you forgot to allocate that array in memory and there after relating its pointer to the variable.
Sample for Array declaration
public static String[][][] realms; /// array variable declared
/*now allocate the memory and point it to the array variable*/
realms = new String [<length index>][<breath index>][<height index>]
try this (replace length index, breath index, height index as per you)
public static String[][][] realms;
#EventHandler
public void onPlayerInteract(final PlayerInteractEvent event) throws Exception {
realms = new String [<length index>][<breath index>][<height index>]
if( event.getMaterial() == Material.NETHER_STAR ) {
int x = (int) event.getClickedBlock().getX();
int y = (int) event.getClickedBlock().getY();
int z = (int) event.getClickedBlock().getZ();
** realms[x][y][z] = event.getPlayer().getName();
createPortal();
}
}
Judging by your comments in other answers, I don't think a multidimensional array is the data structure you want. You suggest your indices are potentially unbounded (or at least very large) and can be negative, and will presumably only be sparsely filled. I think you therefore want an Octree implementation to store your data in. There's one available at http://www.java-gaming.org/index.php?topic=27334.0 - I've never used it, but have used the Quadtree implementation (basically the same thing with 2 dimensions rather than 3) successfully in the past.
Here's an example of how to initialize a multi array:
Initialize 2D array
The bottom of the accepted answer shows the syntax:
String[][] table = new String[5][5];

Categories