What does this code really mean? - java

I made a static method array searcher for int for some pratise to clear myself for making algorithm. I made the static method:
public class ArraySearcher
public static int integerSearcher(int[] arr,int val){
int match = -1;
for(int i = 0; i < arr.length; i++){
if(arr[i]==val){
match = i;
break;
}
}
return match;
}
}
And in the main method I created an array of int and used my static method for finding a defined int in the new int array
int[] anIntArray = { 20, 30, 40, 60 };
int searchingAnArray = ArraySearcher.integerSearcher(anIntArray, 60);
if (searchingAnArray == -1){
System.out.println("match not found");
} else {
System.out.println("result found: "+ anIntArray[searchingAnArray]);
}
The question is that I did'n't understand the System.out.println("result found: "+ anIntArray[searchingAnArray]);" and what does this really means.

The question is that I did'n't understand the System.out.println("result found: "+ anIntArray[searchingAnArray]);" and what does this really means.
It means concatenate the String "result found: " with the int at position searchingAnArray in the array of int(s) anIntArray, then print that String followed by a newline.
You might iterate the array and print its contents like
for (int i = 0; i < anIntArray.length; i++) {
System.out.println("anIntArray[" + i + "] = " + anIntArray[i]);
}
The output (with your provided array) -
anIntArray[0] = 20
anIntArray[1] = 30
anIntArray[2] = 40
anIntArray[3] = 60

System.out.println("result found: "+ anIntArray[searchingAnArray]);
Will look for anIntArray on searchingAnArray position. I.e. will look for the value of the array anIntArray at position 3 (3 comes from your method), then it will print:
result found: 60
If you mean what does + means, is, as #HotLicks said on his comment, a concatenation. It will convert 60 into a String and add it to the same String as "result found: "
Another example:
String name = "Chuck Norris";
System.out.println("Hello " + name);
It will print
Hello you're not Chuck Norris
nah, just joking, it will print:
Hello Chuck Norris
Another example:
int year = 2014, day = 12, month = 8; //This could be done with a date type but for demonstration purposes I'll do it like this.
System.out.println("Today is: " + day + "/" + month + "/" + year);
And will print:
Today is: 12/8/2014
As you can see it will concatenate a String and then an int and so on, then print it.
It could be seen as:
String stringToBePrinted = "Today is: " + day + "/" + month + "/" + year;
System.out.println(stringToBePrinted);
If you call concatenation inside System.out.println(...) it will do something like the above (in an implicit way), something like "creating a local variable" and then print it. (Not exactly that way but you can see it like that to understand it).
Hopefully that is what you're looking for, the best explained as I could.

Related

Adding numbers 1 to n with a loop

So the code posted works and seems to give correct values. The only problem is that it prints every line in the loop instead of just the answer. How can I make it just print the answer instead of every line leading up to it?
import java.util.Scanner;
public class CountLoop{
public static void main (String[] args){
Scanner in = new Scanner (System.in);
int i = -1;
int limit = 0;
System.out.println("Please enter a number");
String end1 = in.nextLine();
int end = Integer.parseInt(end1);
while (i < end){
i++;
limit = (i + limit);
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
}
}
}
I'm fine with using other types of loops as well, as I'll need to show an example with all the different types of loops being used anyway, so any help is appreciated.
Move your system.out.println outside of your while loop
while (i < end){
i++;
limit = (i + limit);
}
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
Or the modern version in Java 8:
int sum = IntStream.range(startInclusive,endExclusive).sum();
System.out.println("The sum of the numbers in between " + startInclusive +
" and " + (endExclusive -1) + " is sum = " + sum);
Renamed variables ;-)
limit -> sum
0 -> startInclusive
end -> endExclusive - 1

why do my simple arrays not work?

This program should ask how many of an animal are left in the wild 5 times. Then it should use a second method to output the same information. But i cant figure this out; every time i change anything based on previous questions here i just add to the number of errors.
import java.util.Scanner;
class animals {
public static void main(String[] args) {
int[] q1 = question();
output(q1);
System.exit(0);
} // exit main
public static int[] question() {
String[] wild = { "Komodo Dragon", "Mantee", "Kakapo", "Florida Panther", "White Rhino" };
int number = 0;
int[] record = {};
for (int i = 1; i <= 5; i++) {
System.out.println(wild[number] + ":");
Scanner scanner = new Scanner(System.in);
System.out.println("How many are left in the wild?");
int howMany = scanner.nextInt();
record = new int[] {howMany};
number++;
}//end for loop
return record;
}// end method question
public static void output(int[] q1){
System.out.println("There are " + q1[0] + " Komodo Dragons in the wild");
System.out.println("There are " + q1[1] + " Mantees in the wild");
System.out.println("There are " + q1[2] + " Kakapos in the wild");
System.out.println("There are " + q1[3] + " Florida Panthers in the wild");
System.out.println("There are " + q1[4] + " White Rhinos in the wild");
}//end method output
} // end class animals
So this compiles alright, then when i've added 5 numbers in terminal after each loop i get
There are 3 Komodo Dragons in the wild
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at animals.output(animals.java:39)
at animals.main(animals.java:13)
Other than the fact that im getting the text, the monodo dragon number being provided is the last number i input not the first
This doesn't make sense
int[number] record = {};
most like what you meant was
int[] record = new int[wild.length];
and instead of
for (int i = 1; i <= 5; i++) {
you need
for (int i = 0; i < wild.length; i++) {
instead of the following which creates an array of 1 value [0]
record = new int[] {howMany};
which will produce the following when you try to access [1]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
you need
record[i] = howMany;
As you write each line of code in your IDE (or your editor) you should see if that compiles and if it doesn't adding more lines is unlikely to help. I suggest you try to compile and test as often as possible so you know where the source of your errors are and when you get a bug, you can step through the code in your debugger to see why the program is not doing what you expect.
This is what you need:
int number = 0;
int[] record = new int[5];
and another modification which you need to make:
int howMany = scanner.nextInt();
record[number] = howMany;
Remove comment from last line.
Now your program should work fine.
Learn some basic stuff about arrays.

why does a string who clearly contains a piece of other, not result in a found hit using .contains()?

this program attempts to scan a text file radio music log, and then match the songs to a directory of wav files. all files are named with the same convention: artist-title, ie: lukebryan-kickthedustup.wav. i swap the locations of the title and artist using the delimiter feature, which allows for easy comparison to the music log, which is already formatted the same way: title, artist.
now, lets say i'm searching the term "lovingyoueasyza", which is Loving You Easy by the Zac Brown Band... when it reaches the file in the directory with the assigned string "lovingyoueasyzacbrownband", it ignores it, even though it contains that string. you'll see i'm calling:
if(searchMe.contains(findMe))
yet it doesn't return a hit. it will return matches if the findMe string only contains the song title, but if any part of the artist title creeps into that string, it stops working. why!? for shorter titles its critical i be able to search for artist name as well, which is why i can't just search by song title.
i've tried using .trim() to no avail. here is some sample output of when a match is found:
searching term: "onehellofanamen"
comparing to: "onehellofanamendbrantleygilbert"
Match found!
value of findMe: onehellofanamen
value of searchMe: onehellofanamendbrantleygilbert
value of y: 49
value of x: 79
here is sample output of a failed attempt to match:
searching term: "lovingyoueasyza"
comparing to: "keepmeinminddzacbrownband"
searching term: "lovingyoueasyza"
comparing to: "lovingyoueasydzacbrownband"
searching term: "lovingyoueasyza"
comparing to: "nohurrydzacbrownband"
searching term: "lovingyoueasyza"
comparing to: "toesdzacbrownband"
searching term: "lovingyoueasyza"
this is what the findMe's go into the method as:
fileToProcess var is: C:\test\06012015.TXT
slot #0: topofhouridplac
slot #1: lovemelikeyoume
slot #2: wearetonightbil
slot #3: turnitoneliyoun
slot #4: lonelytonightbl
slot #5: stopset
slot #6: alrightdariusru
slot #7: lovingyoueasyza
slot #8: sundazefloridag
slot #9: stopset
the final output of matchesFound is like this:
Item Number: 0 ****TOP OF HOUR****
Item Number: 1 d:\tocn\kelseaballerini-lovemelikeyoumeanit.wav
Item Number: 2 null
Item Number: 3 null
Item Number: 4 null
Item Number: 5 ****STOP SET****
Item Number: 6 null
... through 82.
public static String[] regionMatches(String[] directoryArray,
String[] musicLogArray) throws InterruptedException {
String[] matchesFound = new String[musicLogArray.length];
String[] originalFileList = new String[directoryArray.length];
for (int y = 0; y < directoryArray.length; y++) {
originalFileList[y] = directoryArray[y];
System.out.println("o value: " + originalFileList[y]);
System.out.println("d value: " + directoryArray[y]);
}
for (int q = 0; q < originalFileList.length; q++) {
originalFileList[q] = originalFileList[q].replaceAll(".wav", "");
originalFileList[q] = originalFileList[q].replaceAll("\\\\", "");
originalFileList[q] = originalFileList[q].replaceAll("[+.^:,]", "");
originalFileList[q] = originalFileList[q].replaceAll("ctestmusic",
"");
originalFileList[q] = originalFileList[q].replaceAll("tocn", "");
originalFileList[q] = originalFileList[q].toLowerCase();
String[] parts = originalFileList[q].split("-");
originalFileList[q] = parts[1] + parts[0];
System.out.println(originalFileList[q]);
}
for (int x = 0; x < musicLogArray.length; x++) {
for (int y = 0; y < directoryArray.length; y++) {
//System.out.println("value of x: " + x);
//System.out.println("value of y: " + y);
String searchMe = originalFileList[y];
String findMe = musicLogArray[x];
int searchMeLength = searchMe.length();
int findMeLength = findMe.length();
boolean foundIt = false;
updateDisplay("searching term: " + "\"" + findMe+"\"");
updateDisplay("comparing to: " + "\"" + searchMe + "\"");
//for (int i = 0; i <= (searchMeLength - findMeLength); i++) {
if(searchMe.contains(findMe)){
updateDisplay("Match found!");
updateDisplay("value of findMe: " + findMe);
updateDisplay("value of searchMe: " + searchMe);
updateDisplay("value of y: " + y);
updateDisplay("value of x: " + x);
matchesFound[x] = directoryArray[y];
break;
// if (searchMe.regionMatches(i, findMe, 0, findMeLength)) {
// foundIt = true;
// updateDisplay("MATCH FOUND!: "
// + searchMe.substring(i, i + findMeLength));
//
// matchesFound[x] = directoryArray[y];
//
// break;
} else if (findMe.contains("stopset")){
matchesFound[x] = "****STOP SET****";
break;
} else if (findMe.contains("topofho")) {
matchesFound[x] = "****TOP OF HOUR****";
break;
}
}
//if (!foundIt) {
// updateDisplay("No match found.");
//}
}
//}
return matchesFound;
}
It seems to me that your music directory has a bunch of unwanted d's in the file where you put the pieces back together.
searching term: "lovingyoueasyza"
comparing to: "lovingyoueasydzacbrownband"
The comparing to string does not contain the search term because after "easy" there is a "d" which ruins the search which is why you are having errors including artist names.
Here:
searching term: "lovingyoueasyza"
comparing to: "lovingyoueasydzacbrownband"
In your second string, note that there is an extra d after easy.
So the second string does not contain the first string.
I think you are adding an extra 'd' when combining song name with the artist name.
The same thing is happening for all your other strings, e.g.
searching term: "onehellofanamen"
comparing to: "onehellofanamendbrantleygilbert"
which I suppose is one hell of an amen + the extra 'd' + brantley gilbert.

How to display all scores at the end without a loop?

I am trying to display my score at the end of a questionnaire however my way of doing it only displays the last score.
It would work if I were to put it in a loop, the JOptionPane.showMessageDialog however I only want it to display this once, at the end.
Here is my code.
//Main method
JOptionPane.showMessageDialog(null, printPlayerScore(playerName, playerAge, playerScore, playerCount));
//printPlayerScore method
public static String printPlayerScore(String playerName[], int playerAge[], int playerScore[], int playerCount) {
String displayResult = "";
for(int i = 0; i < playerCount; i++) {
displayResult += "\nName: " + playerName[i] + "\nAge: " + playerAge[i] + "\nScore: " + playerScore[i] + "\n";
}
return displayResult;
}
Example run:
Player1: 12
Player2: 12
When it should be
Player1: 10
Player2: 12
I know I need to change the method to something else, but how else could I do it?
Full code: http://pastebin.com/NME8Dh7N
This is a screaming example of the benefits of Object-Oriented Programming. OOP will make this chunk of code easier to debug, read, and write. I'll write some quick code to explain this better (by no means is it perfect). Notice how we can easily create a nice output string using the properties of a Player. Create an array of Player objects, and pass it into your print method.
public class Player
{
public String name;
public int age;
public int score;
public String toString()
{
return String.format("\nName : %s\nAge: %d\nScore: %s\n", name, age, score);
}
}
public static String printPlayerScore(Player[] players)
{
String displayResult = "";
for(Player player : players)
{
displayResult += player.toString();
}
return displayResult;
}
I personally would not code this problem the way you did as it's not OOP and just very confusing. However, here is something you can use so as to not totally break your code but fix your problem.
The main question you are trying to answer is why is the last score showing up. As others have stated, you are using one array for player scores. Here is hack to change your code to get it working:
List<int[]> playerScoresList = new ArrayList<int[]>();
for (int i = 0; i < playerCount; i++)
{
int playerScore[] = new int[1];
JOptionPane.showMessageDialog(null, "It is " + playerName[i] + "'s turn now!");
checkQuestion(question, questionAnswer, userAnswer);
System.out.println("Name: " + playerName[i] + " || Age: " + playerAge[i] + "\n\n ~~~~ Results ~~~~");
System.out.println(printQuestionnaireResults(question, userAnswer) + " ~~~~ End of Results ~~~~\n");
playerScore = calculatePlayerScore(userAnswer, playerScore, playerCount);
// double playerScorePercentage = ((double)playerScore[i] / (double)question.length) * 100;
double playerScorePercentage = ((double)playerScore[0] / (double)question.length) * 100;
System.out.println(playerName[i] + " got " + playerScore[0] + " questions correct out of " + question.length + "! (" +
playerScorePercentage + "%)\n");
playerScoresList.add(playerScore);
}
JOptionPane.showMessageDialog(null, printPlayerScore(playerName, playerAge, playerScoresList, playerCount));
Other methods that need to be changed:
public static int[] calculatePlayerScore(boolean userAnswer[], int playerScore[], int playerCount) {
for (int i = 0; i < 1; i++) {
playerScore[i] = 0;
for (int ii = 0; ii < userAnswer.length; ii++) {
if (userAnswer[ii]) {
playerScore[i] += 1;
}
}
}
return playerScore;
}
And:
public static String printPlayerScore(String playerName[], int playerAge[], List<int[]> playerScore, int playerCount) {
String displayResult = ""; // Maybe use StringBuilder
for(int i = 0; i < playerCount; i++)
{
int[] score = playerScore.get(i);
displayResult += "\nName: " + playerName[i] + "\nAge: " + playerAge[i] + "\nScore: " + score[0] + "\n";
}
return displayResult;
}
Now, you will create a new array with one element each time for each user.
Please keep in mind this hack is provided such that there should be minimal change in your current code. You should seriously consider re-writing the entire program IMO. I've also commented out some other code as well just to get it working.
According to your pastebin, you only have 1 array for storing question answers. Meaning the n+1 player is overwriting n player's answers.
You could either do a matrix (Array of Arrays), or the easier to read alternative, make a class for players and have that class manage player data, with the program having only a list of players. It will reduce the number of parameters in the function calls and allow for easy individualization of answers.
public class Player {
private String name;
private List<boolean> answers;
private int playerId;
}
The matrix would work like this:
boolean answers[][] = new boolean[playerCount][questionCount];
That way, each player has a separate list of answers that independ from each other.
Then, all you need would be to get send each player as a parameter to the functions and read those as necessary.

What's wrong with my code and/or logic?

I having some trouble with an APCS assignment. The program is supposed to read strings with a length of two from a text file - test1.txt - and print out percentages of: a) girl-girl, boy-boy, boy-girl or girl-boy combinations, and b) the total number of individual groups.
I've been trying for an hour to figure this out! Although I'm suspicious of the String declaration in line 25, I don't have a way to confirm that. Furthermore, I'm worried that I messed up my if-else-if-else loop without prompting a compiler error.
The source code is attached for your reference. If you need any additional information, please don't hesitate to ask.
Since I'm a new user with a reputation < 10, please see the attached image:
For elaboration on what isn't working. I took a screenshot and wrote relevant comments on it!
/**
* Family takes user input of sets of boys, girls, and boys + girls. Results are then
* tabulated and displayed in a percentage form to the user. The total number of
* individuals are also displayed.
*
* #E. Chu
* #Alpha
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family {
public static void main (String[] args) throws IOException {
int boyCount = 0;
int girlCount = 0;
double boyGroupCount = 0.0;
double girlGroupCount = 0.0;
int mixedGroupCount = 0;
int totalPersonCount = 0;
double totalGroupCount;
String currentToken = " ";
Scanner inFile = new Scanner (new File ("test1.txt"));
while (inFile.hasNextLine()) {
currentToken = inFile.nextLine( );
if (currentToken == "BG") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "GB") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "BB") {
boyCount += 2;
boyGroupCount++; }
else {
girlCount += 2;
girlGroupCount++; }
}
inFile.close();
totalPersonCount = boyCount + girlCount;
totalGroupCount = boyGroupCount + girlGroupCount + mixedGroupCount;
System.out.println("Sample Size: " + totalPersonCount);
System.out.println("Two Boys (%): " + boyGroupCount / totalGroupCount + "%");
System.out.println("One Boy, One Girl (%): " + mixedGroupCount + "%");
System.out.println("Two Girls (%): " + girlGroupCount / totalGroupCount + "%");
} // End of main method.
} // End of class Family.
currentToken == "BB" should be currentToken.equals("BB")
Don't use == use the method equals instead
Hint: you don't want to compare strings using ==, look into the equals method.

Categories

Resources