I've been coding one of my final school projects related to a text file based on weddings.
I am trying to code a method that will return a wedding object,
(NOTE: weeding object consists of a brideName, groomName, weddingDate, Venue, number of Guests).
In a normal method using Strings. For example, I would merely type
String temp = "";
run a loop to loop through my array. if statement
temp = temp + arr[loop].toString();
return temp;
But now dealing with a wedding object when I declare it:
Wedding temp; - (As i cant initialize it as there is no brideName etc.)
run loop
if statement
temp = temp + array[loop];
return temp;
Here is where i get the error of temp may not have been initialized.
Could anyone help with a suggestion of how to fix this? Thank you so much
Here is what the actual method looks like
public Wedding getWeddingsOnDay(String date, String venue)
{
Wedding temp;
for (int loop = 0; loop < counter; loop++)
{
if (wedArr[loop].getWeddingDate().equals(date) && wedArr[loop].getVenue().equals(venue))
temp = wedArr[loop];
else
temp = null;
}
return temp;
}
Rewrite the method this way.
public Wedding getWeddingAt(String date, String venue) {
for (Wedding w : wedArr)
{
if (w.getWeddingDate().equals(date) &&
w.getVenue().equals(venue)) {
return w;
}
}
return null;
}
Your code will say this obviously beacise it is possible that you code will not go into the if block and temp varialble remain unintilized . So , anyone using it need to check null value before using this temp variable .
There are several ways you can remove this error :
Ignore this error. As this error will not stop running your code .
you can use optional intead of returing null , after this your method will lokks like below method :
public Optional<Wedding> getWeddingsOnDay(String date, String venue){
Optional<Wedding> temp;
for (int loop = 0; loop < counter; loop++) {
if (wedArr[loop].getWeddingDate().equals(date) && wedArr[loop].getVenue().equals(venue)) {
temp = Optional.of(wedArr[loop]);}
else{
temp = Optional.empty();
}
}
return temp;
}
You need not to use temp at all just return wedArr[loop] or null
Related
The class is called Exposicion and has a String and an INT value, so I used it as an array to grab some input from the user.
class Exposicion {
public String nombreExpo;
public int duracionExpo;
Exposicion(String nombreExpo, int duracionExpo) {
this.nombreExpo = nombreExpo;
this.duracionExpo = duracionExpo;
}
}
With the Function SortExpo I plan to copy only the values of the array as long as the INT values don't add up to 180, but java flags an error when doing:
arrExpoT[posHor].nombreExpo = arrExpoS[k].nombreExpo;
This is the whole function
void SortExpo(Exposicion[] arrExpoS,int posicion,Exposicion[] arrExpoT){
int poshor=0;
int total=0;
for (int k = 0; k < posicion; k++) {
if ( total < 180 || arrExpoS[poshor].nombreExpo != "TOMADO123") {
arrExpoT[poshor].nombreExpo = arrExpoS[k].nombreExpo;
arrExpoT[poshor].duracionExpo = arrExpoS[k].duracionExpo;
arrExpoS[poshor].nombreExpo = "TOMADO123";
total = total + arrExpoS[k].duracionExpo;
poshor++;
} else {
k = posicion;
}
}
}
Error
I've added the .java file in this link
Also Main.java if this helps
You are getting a NullPointerException because "expo1" and "sala1" variables are both null. You have to pass a reference to an object on both variables. Something like this:
class SalaExpo(){
Exposicion[] expo1=new Exposicion[100];
}
public class ConsoleMenu {
private SalaExpo sala1;
void execute(){
sala1 = new SalaExpo();
}
}
Also you should poblate the sala1.expo1 array, like this (don't know if this is what you are intending but you should do this in order not to get a NullPointerException) :
void GuardarExpo(Exposicion[] arrExpoG,int posicion,Exposicion[] arrSala) {
/*
Bunch
of
code
*/
arrExpoG[posicion] = new Exposicion(inputNombre,inputDuracion);
arrSala[posicion]=arrExpoG[posicion];
}
Finally, you should use the variable "posicion" instead of "sala1.expo1.length" to pass as argument to the "imprimirExpo" method, since the array "sala1.expo1" has a length of 100, that means a lot of null elements since you are not poblating it all:
ImprimirExpo(sala1.expo1,posicion);
instead of:
ImprimirExpo(sala1.expo1,sala1.expo1.length);
I put in the return statement for both cases, if and else
but it's still says that the return statement is missing
What's wrong with my code?
public static getNext(){
ArrayList<String> copy = new ArrayList<String>();
Random dice = new Random();
int rolls;
for(int x=0; x<i.length; x++){
copy.add(i[x]);
}
if(copy.size() < 1){
return "NONE";
}
else{
rolls = dice.nextInt(copy.size());
return copy.get(rolls);
copy.remove(rolls);
}
}
else{
rolls = dice.nextInt(copy.size());
return copy.get(rolls);
copy.remove(rolls); <--- UNREACHABLE
}
Your compiler probably missed the return statement due to unreachable line of code after the return.
Also, you haven't declared the returned class. There should be:
public static <return type> methodName(<parameters>) {
<body>
}
Q: How could I remove the copy.get(rolls) after returning it? Is there a way?
A: Basically the question is about the concept of functions. Function is a piece of code which performs some logic and then, based on it returns something. Return statement is the last thing that happens in the function.
You can also have a block of code which doesn't return anything, but takes parameters. These are called procedures. Anyway, in Java we call both of them: functions and procedures methods.
You have some misunderstood in your code :
First when you make return the method should return something
Second you can't specify any kind of statement after your return
Third you have to store your return value that you want to remove it and return it in a separate variable
Your code should look like this :
public static String getNext() {
//-------------^^------------return type
ArrayList<String> copy = new ArrayList<String>();
Random dice = new Random();
int rolls;
for (int x = 0; x < i.length; x++) {
copy.add(i[x]);
}
if (copy.size() < 1) {
return "NONE";
} else {
rolls = dice.nextInt(copy.size());
String s = copy.get(rolls);//<<----------put the val you want in separate variable
copy.remove(rolls);//<<-----------remove your val
return s;//<<-----------return your val
}
}
Note
Like #BackSlash mention in comment, it is useless to remove your val from your list, because it will not used after you get out of your method, so if you are using this List in another place you have to declare it outside your method for example :
private static ArrayList<String> copy = new ArrayList<String>();
public static String getNext() {
//ArrayList<String> copy = new ArrayList<String>();//<<<-------------useless position
....
So I've been trying to figure this out on my own for the past couple of hours but I'm stuck.
I have an array that has a list of a person's name, age, height (in cm). I want to create a method where I use only the person's name as a parameter and searches for the name in the array; if there is no matching name, return null.
Looks like this:
data = new data[50];
data[0] = new data("Dan", 23, 179);
data[1] = new data("David", 20, 180);
data[2] = new data("Sharon", 19, 162);
data[3] = new data("Jessica", 22, 160);
data[4] = new data("Nancy", 25, 164);
...
numberData = 30; // this is the number of people that are in this array so far
This is what I've been trying so far..
public data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name == data[i]) {
return data[i];
} else {
return null;
}
}
}
I know it isn't right, but I can't seem to find a solution. Any ideas?
array is referencing the Data class with name parameter so we should compare with name parameter not directly with reference of data and for string comparisons always go for equals() method.
public Data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name.equals(data[i].getName())) {
return data[i];
}
}
return null;
}
Since you want to compare strings you must use the equals method.
Here's an example of how can you use java 8:
public Data findData(Data[] datas, String name) {
return Arrays.stream(datas).filter(data -> data.getName().equals(name)).findAny().orElse(null);
}
In case the loop doesn't execute at least once, you're missing return value.
== compares references, equals compares Strings.
Return null just in case, there is no such element in the array.
Class names should start with a capital letter. Please write Data instead of data.
Code:
public Data findData(String name) {
for (Data d : data) {
if (name.equals(d.getName())) {
return d;
}
}
return null;
}
is what you're looking for. In the original code, null was returned if the 0th element wasn't name.
OK, the above was a quick fix and now some theory:
The pseudo code for linear search in an array:
Loop through all elements in an array. If any matches with the one you're looking for, return it.
If nothing was returned, return the indicating value (null in our case).
Look, in the original code, on the 0th element, you decided whether to return that element or a null. Also, if the loop wasn't run at least once, there was no return statement to hit.
Use equals() to compare strings,
e.g.
if(name.equals(data[i].getName())) {
statements...
}
You should use equals() to compare strings. equals() checks the actual contents of the string, == checks if the object references are equal.
And also, as mentioned above, move return null outside the loop;
You can use following code. Assuming that your data class will have getName() method which returns the name value.
public data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name.equals(data[i].getName())) {
return data[i];
}
}
return null;
}
move the return null statement out of the loop.
Oh! and yes, use the equals() method instead of ==
EDIT :
ok, sorry for not so clear question. Let's try other way:
We have an ArayList of names : Peter, John, Adam
We are looking for String name;
If ArrayList contains the String, we want to write the String. If ArrayList doesn't contains the String, we want to add the String into the ArrayList.
If I'm looking for "Adam", then this program is not working, because first it finds name "Peter", then "John", and only after that it finds "Adam". So for the first 2 times, it thinks, "Adam" is not in the list, and acts so.
String findName;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().contains(findName)) {
System.out.println(findName);
break;
}
else
arrayList.add(findString);
}
Original question :
I have a String and an Array (ArrayList). I have to do something, if the String is in the Array and something else, if it is not in the Array. How do I do that?
I can't do it like this :
String myString;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().equals(myString)) {
DO SOMETHING;
break;
}
else
DO SOMETHING ELSE;
}
because it will find the String only once and all the other times it will act, like the arraylist doesn't contains the String.
So I'm doing it like this :
String findString = "0";
String myString;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().equals(myString)) {
DO SOMETHING;
findString = "2"; //when I find the String, I change this
break;
}
if findString == "0"; //if I have not found the String, this happens
DO SOMETHING ELSE;
}
and I have the feeling, it should be not done like this. ;)
I know I can use booleans instead of this way, but it's the same in other way. Isn't there total different way of doing this correctly?
Cleanest way is as follows: Declare a method which returns whether the string is in the array:
public boolean arrContainsStr(String str, String[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(str)) {
return true;
}
}
return false;
}
Then use this method in your code like this:
String myString;
String[] myArray;
if (arrContainsStr(myString, myArray)) {
DO SOMETHING;
}else {
DO SOMETHING ELSE;
}
This is for primitive string arrays. Note that if you are using an ArrayList or similar, you can simply use the .contains(myString) method to check if the list contains your string. Documentation here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object)
This question is a bit odd, but just reading your first sentence, if you want to see if a List e.g. ArrayList contains an object (e.g. a String) you can just use the contains(Object o) method rather than looping through. I must be missing your point. In any case, an example:
String stringToFind = "Foo";
List<String> stringList = new ArrayList<>();
stringList.add("Foo");
if (stringList.contains(stringToFind)) {
System.out.println("String found");
} else {
System.out.println("String not found");
}
Output: String found. (In this example).
Couldn't you use .contains as below to check if the String is in the list?
if(arrayList.contains(myString)){
// DO SOMETHING
} else {
// DO SOMETHING ELSE
}
You could set a boolean to true if you find your value then break.
If you don't find the value, the boolean will stay to false.
Then you do the if
Its a little vague so I'm not sure if this is what you want, but if you remove the break in the first segment of code i think you will get what you want. do you want it do DO SOMETHING for every occurrence of the string or just the first one. also if you do need the break you could check the value of i after the loop terminates so
if(i==arrayList.size())
{
//String found
}
else
{
//String not found
}
I hope someone could help me please, I need to pass a String from the method below to the method below that. I have looked on the interent and got it working on test programs but can't seem to get it working on mine, it's been 3 hours, 3 pages of google and a book lol. Sorry if this is easy but I really have no idea.
What I need to do... I need to pass the variable "Hex" from the method "WMDBAudio" to the method "hexConverter". I hope this makes sense, thanks for your help in advance it's is apperciated!
public class WMDBAudio{
public String WMDBAudio1(String fileInfo) throws IOException{
//code removed as there is quite a lot
int m = 0;
while (m != 1){
for (int count = 0; count < 3; count++){
hexIn = in.read();
s = Integer.toHexString(hexIn);
if(s.length() < 2){
s = "0" + Integer.toHexString(hexIn);
}
temp = temp + s;
}
if ("000000".equalsIgnoreCase(temp)){
m = 1;
hex = entry;
}
entry = entry + temp;
temp = "";
}
}
}
//Hex Converter method
public class hexConverter{
public static void hexConverter(String t){
WMDBAudio w = new WMDBAudio();
String hex = "";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2){
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);
}
}
By convention you name Java classes starting with upper cases. So hexConverter should be renamed to HexConverter.
You generally invoke another class from a class in this format:
MyClass myClass = new MyClass();
after that you can use myClass object to access methods (not private) of MyClass.
Make the following 2 lines change as I have commented.
public class WMDBAudio{
public String WMDBAudio1(String fileInfo) throws IOException{
//code removed as there is quite a lot
int m = 0;
while (m != 1){
for (int count = 0; count < 3; count++){
hexIn = in.read();
s = Integer.toHexString(hexIn);
if(s.length() < 2){
s = "0" + Integer.toHexString(hexIn);
}
temp = temp + s;
}
if ("000000".equalsIgnoreCase(temp)){
m = 1;
hex = entry;
}
entry = entry + temp;
temp = "";
}
//add these 2 lines
hexConverter hexConv = new hexConverter();
hexconv.hexConverter(hex);
}
}
You could set hex as a private attribute of the class, thus being acessible to both methods (and all others of the same class).
This assuming that calling the first one doesn't necessarily require calling the second one. If that's the case then you could just call hexConverter from WMDBAudio with an extra parameter for the hex String.
EDIT: Nvm that just saw they are two different classes. Well, you could save the hex as a private variable on both classes and have a GetHex() method on the WMDBAudio class. You then use the value returned by that method to create a hexConverter class that takes Hex as a parameter to its constructor thus allowing something of the sort:
WMDBAudio audio = new WMDBAudio()
...
hexConverter hexconv = new hexConverter(audio.GetHex())
Or just supply an additional parameter to the hexConverter function allowing you to write something like this:
WMDBAudio audio = new WMDBAudio()
...
hexConverter hexconv = new hexConverter()
hexconv.hexConverter(audio.GetHex())
Since hexConverter is a static method in hexConverter class,
you can access the method as
hexConverter.hexConverter(hex);
You need not create a new object to access the method. The method performs a common operation and does not change the state of the object. Hence, you can use it as above, pass the String and get the result.
You might also need to import hexConverter class if it is in a different package.