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

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.

Related

Trying to pass an array to a different class in Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm creating a lottery program and trying linked lists for the first time. I'm passing the numbers array from the Player class to the Lottery class so that I can display the current players Numbers, but it keeps giving me the error "actual and formal parameters differ in length".
There will be another class which will be made for the winning numbers but I'm trying to fix this issue first. I'm unsure how to fix this as I've been stuck for quite a while now.
Any help would be much appreciated.
This is the piece of code I'm having trouble with, this is in the Lottery class in the displayPlayers() method -
for(int i = 0; i < 6; i++) {
System.out.println(currentPlayer.getNumbers(i));
}
public class LOTTERY
{
Scanner keyboard = new Scanner(System.in);
private PLAYER pHead;
public LOTTERY()
{
pHead = null;
}
public void displayPlayers() {
PLAYER currentPlayer = pHead;
System.out.println("Name: " + currentPlayer.getName());
System.out.println("Age: " + currentPlayer.getAge());
currentPlayer.randNum();
System.out.println("Your Numbers: ");
for(int i = 0; i < 6; i++) {
System.out.println(currentPlayer.getNumbers(i));
}
menu();
}
public void runProg() {
displayPlayers();
}
public static void main(String[] args) {
LOTTERY lottery = new LOTTERY();
lottery.runProg();
}
}
The method getNumbers() does not take an parameters but you are trying to pass it i. Additionally, this method returns an array, so you want to get this before the loop iteration, then iterate through it.
You can do this easily using an enhanced for loop:
for (int currentNum : currentPlayer.getNumbers()) {
System.out.println(currentNum);
}
Or with a standard for loop:
int [] arr = currentPlayer.getNumbers();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
The error you are getting says it all, the method you wrote takes no parameters. When you call your getNumbers() method, you pass it the value of i, though java does not expect that, since you declared the method without any parameters.

Create bubble sort code, but facing some errors [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 6 years ago.
Improve this question
Had a problem with compilation, getting error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at practise.code.main(code.java:11)
Here is my code:
package practise;
public class code {
static int number[]={1,8,5,9,4,7};
static int c[] = new int[number.length];
static int p=0;
static int q;
public static void main(String[] args){
change(number);
System.out.println("Array Before Bubble Sort");
for(int y: c){
System.out.print(y + "\t");
}
}
public static void change (int x[]){
for(int a: x){
for(int i=0; i<=x.length; i++){
if(a > x[i]){
continue;}
else {
p++;}
q = x.length - p - 1;
c[q] = a;
}
}
}
}
}
Some meta-help for future reference:
Compiler errors: these are when you experience an error that occurs at compile time. For Java, this is when you use javac, and your Java code is being turned into bytecode files for interpretation later.
Runtime errors: this is when you experience an error that occurs when you run your code. For Java, this is when you use java, and your Java code is being run.
If you find the two confusing, add into your question the thing you typed in order to experience the error. Specify all the flags and options you used, and format it with a code block, for example like this:
java -jar code.jar
When asking questions here - or indeed anywhere on the web where you can get technical help - try to ask yourself what clarifications you would need if you saw your question for the first time. Your first edit did not include your code, so ask yourself: would you be able to ascertain someone else's similar problem without code? Broadly here the answer is "no", and thus the moral of this story is: always include your code.
Also, do spend a moment to learn the code formatting tools. To use them, paste your block of code into the question, select it, and click the "code" button. It will apply a four-space Markdown indent, which you can now see in the question.
If you need to add clarifications to your post, it is OK to add them as comments, but do also edit the body of the question so that new readers can understand the question. It is well worth spending time making it as readable and clear as possible, so you can get the best possible help, and so that people do not take a look and decide that another question is a better use of their time.
Since you are using an IDE, do you get any warnings/errors in the editor, to help you identify potential problems in you code? If so, and you do not understand them, then paste them into your question, in order to clarify it.
Thanks for your advices... Finally made it working..
thank you once again
package practise;
public class code{
public static void main(String[] args){
int[] Array = {5,8,6,4};
int[] newArray = new int[Array.length];
int a, b, c, d, e, f =1;
for(int z : Array ){
d=0;
for(int i=0; i<Array.length; i++){
a = z; b = Array[i];
if( a >= b){
continue;}
else{
d++;}
}
c = Math.subtractExact(Array.length , d);
e = Math.subtractExact(c, f);
for(int j=0; j< Array.length; j++){
while( j == e){
newArray[j] = z;
break;
}
}
}
System.out.println("Here is your old Array :");
for(int k : Array){
System.out.println(k);
System.out.println("Here is your new Bubble Sort Array :");
for(int q : newArray){
System.out.println(q);
}
}
}
}

No error yet no output. Help.(Sudoku solver getter) [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 7 years ago.
Improve this question
I want to add text fields a01, a02, ... to the array a.
I want to display the value of val so that I would know if the text is being taken from text fields. This code does not show any errors, but, well, it doesn't give me output as well.
int i, j;
JTextField[][] a = new JTextField[9][9];
int[][] val = new int[9][9];
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
{
val[i][j] = Integer.parseInt(a[i][j].getText());
System.out.println(val[i][j]);
}
}
It is from my old question here.
You did not give them value
int i,j; // counter
JTextField[][] a = new JTextField[9][9];
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
JTextField tf = new JTextField();
tf.setText("a"+i+j);
a[i][j] = tf;
}
}
In your version the call to a[i][j].getText() should throw a NullPointerException. This should either kill your application, end up on the console or you have somewhere something like
try {
// more code here
} catch (Exception ex){}
which will silently swallow the exception and is veeeeery bad practice.
The code you have shown us does generate an error - it throws a NullPointerException when you try to access the text of the text fields via a[i][j].getText().
You didn't initialize the JTextFields in your array a.
ideone example

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.

Is it possible to insert data in a the second array when the first one is full? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am practicing Java and working on arrays. As arrays size can not be changed in run time, is it possible to make 2 arrays and in run time keep storing input in the first of and then when it is full, then move to the second array by if statement. I'm basic in Java so hope my code is in the right direction. Anyway it does not work but I just want to share my idea and see if it can work.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int[] arr1 = new int[5];
int[] arr2 = new int[10];
while(in.hasNextInt())
{
for(int i = 0; i <= arr2.length; i++)
{
if (i <= arr1.length) { arr1[i] = in.nextInt(); }
else arr2[i] = in.nextInt();
}
}
}
You should change your code to the following:
if (i < arr1.length) { arr1[i] = in.nextInt(); } //"<" instead of "<="
else { arr2[i - arr1.length] = in.nextInt(); } //decrement i by the size of the first Array
As denoted in the other answer/answers, there are plenty of more practical ways to do what you are trying to achieve, but non the less the above should let your code work as inteded.
This is not a good idea. If the second array overfills, you'll have problems such as exceptions and lost data.
I recommend using the ArrayList.
You can create one:
ArrayList<Integer> list=new ArrayList<>();
and add to it with:
list.add(new Integer(in.nextInt()));
With autoboxing you can skip the creation of an integer reference object and use:
list.add(in.nextInt());
Anyway it does not work ...
Yea. Pretty obviously.
... but I just want to share my idea and see if it can work.
No. Pretty obviously.
Sure you can put elements in the second array when the first array. But then you run into the same problem all over again when when the second array fills up.
The best solution is to use an ArrayList<Integer> (... or any kind of List<Integer>). That will take care of the problem of "growing" the list transparently and automatically.
If you insist on doing this with arrays, then the solution is to:
dynamically allocate a "new" array that is bigger than the "current" array,
copy the elements of the "current" array to the "new" array, and
assign the reference for the "new" array to the "current" array variable.
In fact, you could do all of this using Arrays.copyOf(int[], int).

Categories