Value of Variable Not Updating [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
My Variable c is always zero. I dont understand why its not updating. can anyone please explain why this is happening. what should i do to avoid this
public static int linearSearch(Exam[] marks, String name) {
int c =0;
if( marks==null)
{
return -1;
}
else{
for(int i=0;i<marks.length;i++)
{
//System.out.println(a[i]);
if(performances[i].getName()==name)
{
c= i;
}
}
}
return c;
//to be completed
}

Modify this line as below
performances[i].getName().equalsIgnoreCase(name)
if you want to Ignore upper or lower case
else use the below
performances[i].getName().equals(name)
to check the content of the name instead of references.

Related

I have a problem with "variable may not have been initialized" despite having an if/else statement (initialization in both cases) [duplicate]

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Why does this code keep returning a "variable might not have been initialized" error?
(2 answers)
Java variable might not have been initialized? [closed]
(4 answers)
Closed 2 months ago.
protected int getGewichtung(String company)
{
int index;
for (HashMap<String,String> i : top3Compland)
{
String test = String.join(_name, i.keySet());
System.out.println(test);
if (test == company)
{
index = top3Compland.indexOf(i);
}
else
{
index = -5;
}
}
return index;
}
I have checked with print statements whether it is entering the for-loop at all. But all the keys are being printed out so it does enter it and also the conversion to a string does take place and as I am at first putting only valid strings to the function it also must enter the if statement for sure but if even it doesn't then it would be enter the else statement and initialize it with a number so it should't be complaining about the variable "index" possibly not being initialized. What am I overseeing?? Thank you for your help!
updated Version: I improved some flaws, but the same error is arising. But I cannot fathom a case in which index is not being initialized...
protected int getGewichtung(String company)
{
int index;
if (top3Compland.size() > 0 && top3Compland != null)
{
for (HashMap<String,String> i : top3Compland)
{
String test = String.join(_name, i.keySet());
System.out.println(test);
if (test.equals(company))
{
index = top3Compland.indexOf(i);
}
}
}
else
{
index = -5; //company not found
}
return index;
}
You do have an initialization in both if/else statements, however this only applies when you enter the foreach loop. When top3Compland is empty the program doesn't enter the loop and the variable index is never initialized.

what code can i use to clear the screen(java)? [duplicate]

This question already has answers here:
commands in java to clear the screen
(11 answers)
Closed 5 years ago.
I'm writing a text-based unit converter and I want to be able to run a clear command so that the window that the program I want to know how I can do it.
I think you can System.exec("clear") but that depends on what operating system the program is running on.
This is my choice for clear:
public static void clearConsole() {
String value = "\n\r";
for (int i = 0; i < 5; ++i) {
value = value + value;
System.out.printf(value);
}
}

fun(agr++) vs fun(arg+1) in java [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 6 years ago.
I was trying to reverse String using recursion as follows.
But when I am calling reverse(arr,start++,end--) it is giving stackoverflow error.
I tried using reverse(arr,start+1,end-1) then it is working fine.
public class Reverse {
public static void main(String[] args) {
char inp[] = "TestString".toCharArray();
int n = inp.length;
reverse(inp, 0,n-1);
System.out.println(String.valueOf(inp));
}
public static void reverse(char[] arr, int start, int end){
if(start>=end)
return ;
char tmp;
tmp = arr[start];
arr[start] = arr[end];
arr[end] = tmp;
reverse(arr,start+1,end-1);//error line
}
What is the problem with reverse(arr,start++,end--)?
I want to know why value of start++ and end-- will not get passed to function.
Have a look at this SO question
SO post-increment-and-pre-increment-concept
Post
reverse(arr,start++,end--) when you do this the incremented/decremented value will not be passed to recursive method, means you are calling the method with original value of start and end result in SO error
Pre
When you do reverse(arr,start+1,end-1) or reverse(arr,++start,--end) incremented and decremented value of start and end will be passed to recursive method.
While debugging in Eclipse IDE check the values of start and end in variables panel if not using IDE write start and end values to console in reverse method

Working with Generic arrays [duplicate]

This question already has answers here:
Java generics and Array's
(5 answers)
Closed 8 years ago.
Good day. I have been learning java the last few months. So I created a generic array as follows.
public class Implementation<T> implements IMatrix<T>{
private T[][] genMatrix;
private Integer numberRows;
private Integer NumberCols;
public Implementation(){
generateMatrix();
for(int i = 0;i< numberRows;i++)
{
for(int j =0;j< numberCols;j++)
{
JOptionPane.showInputDialog("Enter value for row " + (i+1) + " and for column " + (j+1)))
}
}
multiplyScalar(5);
}
//generate the array
public void generateMatrix(){
String rowString = JOptionPane.showInputDialog("Enter the number of rows!");
numberRows = Integer.parseInt(rowString);
String colString = JOptionPane.showInputDialog("Enter the number of cols!");
numberCols = Integer.parseInt(colString);
final Object[][] arrayO = (T[][])new Object[numberRows][numberCols];
genMatrix = (T[][])arrayO;
}
//writeElements to the array;
public void writeElem(int x, int y, T value){
genMatrix[x][y] = value;
}
//now that those members are done I have created a method to access the data
public T getElem(Integer i, Integer j){
return (T)genMatrix[i][j];
}
This is where my problem now exists. I have made this two dimensional array. I would like to multiply each value in this array by a Integer c. I have attempted it in the following way and all failed.
public IMatrix<T> multiplyScalar(Integer c) throws MatrixException {
// TODO Auto-generated method stub
for(int i = 0; i< numberRows; i++)
{
for(int j=0;j<numberCols;j++)
{
/**
THIS IS THE POINT AT WHICH IT CRASHES
*/
System.out.println(((Integer)(getElement(i, j)) * c));
}
}
return null;
}
}
The program crashes because of a ClassCastException. I have tried everything in my knowledge to get this to work. I can not multiply the two dimensional array with a Integer. Please help. This uses a interface with many more functions that is irrelevant. Please note that there is a strong possibility that this code crashes as I can not upload the original code.
The problem is that Java doesn't support operator polymorphism. You need T to extend Number and then use method calls. Its a bit more verbose than what one might like though. Its explained quiet well here:
Predefining multiplication for generics in java

How can i avoid ArrayIndexOutOfBoundsException in this case? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
Is it possible to avoid ArrayIndexOutOfBoundsException in this case ??
package com;
public class Hi {
public static void main(String args[]) {
String[] myFirstStringArray = new String[] { "String 1", "String 2",
"String 3" };
if (myFirstStringArray[3] != null) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}
}
}
Maybe I don't understand the real problem, but what prevents you to check if the index is inside the array before accessing it in this case?
if (myIndex < myFirstStringArray.length) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}
In arrays, they are measured differently than numbers. The first object inside an array is considered 0. So, in your if statement, instead of a 3, you just put a 2.
if (myFirstStringArray[3] != null) {
System.out.println("Present");
to
if (myFirstStringArray[2] != null) {
System.out.println("Present");
Hope this helps! :)
Your String array contains 3 elements and you are accessing array[3] i.e. 4th element as index in 0 based and so you get this error (Exception, anyway).
To avoid the ArrayIndexOutOfBoundsException use an index within specified index range. And always check whether your index is >= array.length.

Categories

Resources