My program is suppose to take a text file, read the first four names, create a random number between 1-4, and then assign the names to 4 different teams based on what the random number was. For instance, if the number was 3, then the first name would go to team 3, second name to team 4, etc. etc.(repeat process until there are no more names) I believe I have all of the code for that correct, the problem is I can't figure out how to return all the names I have put into the arrays that were brought into the method. Here is my code:
public static void main(String args[]) throws IOException
{
BufferedReader girlFile = new BufferedReader(new FileReader("girls40.txt"));
PrintWriter teamFile = new PrintWriter(new FileWriter("xxxxxxx-teamlist.txt"));
String team1[] = new String[20];
String team2[] = new String[20];
String team3[] = new String[20];
String team4[] = new String[20];
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
}
public static String[] loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile)
{
int n;
int random;
String name1;
String name2;
String name3;
String name4;
while((name1=girlFile.readLine())!=null)
{
name2=girlFile.readLine();
name3=girlFile.readLine();
name4=girlFile.readLine();
random = 1 + (int)(Math.random() * 4);
if(random==1)
{
team1[n]=name1;
team2[n]=name2;
team3[n]=name3;
team4[n]=name4;
}
if(random==2)
{
team1[n]=name4;
team2[n]=name1;
team3[n]=name2;
team4[n]=name3;
}
if(random==3)
{
team1[n]=name3;
team2[n]=name4;
team3[n]=name1;
team4[n]=name2;
}
if(random==4)
{
team1[n]=name2;
team2[n]=name3;
team3[n]=name4;
team4[n]=name1;
}
n++;
}
return team1[],team2[],team3[],team4[];
}`
The main method was given to me, so it cannot be changed.
If there is more code in main method than you've posted here. You'll have to mention what is the variable n and how is it being used else follow the answer.
main Method can't be changed
In your main method,
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
} // End of Main Method
You have not used returned value n for nothing. So it really doesn't matter what you return from method loadTeams() as long as it is an int.
Also, here loadTeams() returns an String[] which can't be assigned be int n, you'll have to change return type of loadTeams() to int as
public static int loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile) {
/*
...
*/
return 0; // whatever, it isn't being used
}
This the solution if you can't change the main method.
The call to loadTeams() expects a return value of type int. Not an array or multiple arrays. If you can't change the main method then loadTeams should return an integer.
// ...
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
// ...
you don't have to return anything, arrays created in main() will be passed to your method by reference, you can fill them there, and after execution of your method, values will be kept in these arrays
The loadTeams should return an int and not String[].
There is no need to return arrays. Changes made in the arrays in the loadTeams methods will be reflected back to the array in main method.
Related
I'm struggling a bit here. I need to take an I.P address supplied as a string and store as a dotted decimal. split it into its 4 octets that need to be stored as int variables. Which I believe I've done here in its constructor and then using a presupplied driver method return each octet. I can't figure out how to access and send them in the "getOctet" method.
Heres the class file:
public class IpAddress
{
private String dottedDecimal;
private int firstOctet;
private int secondOctet;
private int thirdOctet;
private int fourthOctet;
//**************************************************************
public IpAddress()
{ } // end 0 parameter constructor
//*************************************************
public IpAddress(String d)
{
this.dottedDecimal = d;
String[] ipArr = dottedDecimal.split("\\.");
this.firstOctet = Integer.parseInt(ipArr[0]);
this.secondOctet = Integer.parseInt(ipArr[1]);
this.thirdOctet = Integer.parseInt(ipArr[2]);
this.fourthOctet = Integer.parseInt(ipArr[3]);
} // end 1 parameter constructor
//************************************************************
public String getDottedDecimal()
{
return this.dottedDecimal;
}
//********************************************************
public String getOctet(int n)
{
}
Here is the driver method I have to use unchanged:
public static void main(String[] args)
{
IpAddress ip = new IpAddress("216.27.6.136");
System.out.println(ip.getDottedDecimal());
System.out.println(ip.getOctet(4));
System.out.println(ip.getOctet(1));
System.out.println(ip.getOctet(3));
System.out.println(ip.getOctet(2));
} // end main
Any guidance would be greatly appreciated. I think I have to use an array, which I've tried but I don't exactly know how to use, Arrays are technically the next module we're learning after this assignment so I haven't actually learned how to use them yet
I did this for getOctet method and it seems to work.
It isn't exactly elegant but it worked
public int getOctet(int n)
{
int arr[] = new int[5];
arr[0] = 0;
arr[1]= this.firstOctet;
arr[2]= this.secondOctet;
arr[3]= this.thirdOctet;
arr[4]= this.fourthOctet;
return arr[n];
} // end getOctet
I am new to Java programming and I had a task in class.
So the main thing was I had to make a public class named BankAccount with these 3: int number, String owner, int amount.
Then I had to make an array of 10 with this class and fill it up (the owner names were Name1, Name2, etc.).
Then I had to make a String array of 5 with 5 names in it (for example: "James", "Jack", etc.)
and then I had to kind of "modify" the owner names so that my program will attach one of the 5 names randomly to the end of the current owner names.
So it will be like this for example: Name2Jack, Name3James, etc.
I successfully did all of this.
But then.
My teacher told me to make another method which will decide, how many names do I have out of the 10 ownernames in which name X is present.
So I did this:
public static int Count(BankAccount[] accounts, String name){
int number=0;
for (i=0; i<accounts.length, i++){
if(accounts[i].owner.contains(name)==true)
number++;
}
return number;
}
At least if I remember correctly, it was this. Or something similar like that.
And this worked as well.
But then, my teacher said, how would I do it with not .contains but with .equals ?
And if I would do it with that, would I need 1 or 2 "=" marks?
I had no idea what she means, like I dont know how to do it with .equals... because the owner names are like Name1Jack for example..
She told me I would need 1 "=" mark instead of 2, and that I should look after this for the next class.
Can you guys actually tell me what she meant with this ".equals" method instead of the .contains one?
How could I do this with .equals , and I dont get it why would I need 1 "=" mark instead of 2 whatsoever.
Any help would be really appreciated!
It appears that you need to just change this one line:
From:
if (accounts[i].owner.contains(name) == true)
To:
if (accounts[i].owner.equals(name))
Here is a sample code with both variations:
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount[] bankAccounts = new BankAccount[5];
bankAccounts[0] = (new BankAccount(1, "Name1James", 1000));
bankAccounts[1] = (new BankAccount(2, "Name2Jack", 2000));
bankAccounts[2] = (new BankAccount(3, "Name3Henry", 3000));
bankAccounts[3] = (new BankAccount(4, "Name4Jack", 4000));
bankAccounts[4] = (new BankAccount(5, "Name5James", 5000));
System.out.println("Check A:");
System.out.println(BankAccountDemo.Count(bankAccounts, "James"));
System.out.println(BankAccountDemo.Count2(bankAccounts, "James"));
System.out.println("Check B:");
System.out.println(BankAccountDemo.Count(bankAccounts, "Name5James"));
System.out.println(BankAccountDemo.Count2(bankAccounts, "Name5James"));
}
public static int Count(BankAccount[] accounts, String name) {
int number = 0;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].owner.contains(name) == true) {
number++;
}
}
return number;
}
public static int Count2(BankAccount[] accounts, String name) {
int number = 0;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].owner.equals(name)) {
number++;
}
}
return number;
}
}
Run output is:
Check A:
2
0
Check B:
1
1
I have this method that adds temp to xy array.
public void printBoard(int temp[][],int type){
if(type == 1) {
xyArray.add(new Array(temp));
numberOfSolutionsXY++;
}
}
xyArray is global and declared as
public ArrayList<Array> xyArray = new ArrayList();
When I check its value before exiting the method printBoard, it prints the expected 2d array. But when I go to another method, the value of xyArray is different. It has the value of the other Arraylist.
I checked back and forth many times, I did not just mistype the parameter. It's not happening only on xyArray, the same happens to other arraylists: regArray, xArray and yArray
This is how I check the value
System.out.println("\n xy \n"+xyArray.toString());
I do solveBoard method and tries to add the expected value of arrays but different values were appended. They were all the same.
problemArray.add(new Array(board));
solveBoard(board,0,0,4);
if(numberOfSolutions>0)
solutionArray.add(new ArrayList(regularArray));
solveBoard(board,0,0,3);
if(numberOfSolutionsX>0)
solutionArray.add(new ArrayList(xArray));
if(dimension%2==1){
solveBoard(board,0,0,2);
if(numberOfSolutionsY>0)
solutionArray.add(new ArrayList(yArray));
solveBoard(board,0,0,1);
if(numberOfSolutionsXY>0)
solutionArray.add(new ArrayList(xyArray));
}
solutionsArray.add(new ArrayList(solutionArray));
System.out.println("\nsolutions\n"+regularArray.toString());
All of them have the value of problemArray. Even though i placed problemArray.add(new Array(board)); at the bottom, they still get its value.
This is the class Array i've made
public class Array {
int[][] array;
public Array(int[][] initialArray){
array = initialArray;
}
public String toString(){
String x = "";
for(int i = 0;i<array[0].length;i++){
for(int j = 0;j<array[0].length;j++)
x+=array[i][j];
x+="\n";
}
return x;
}
}
Full code here
Try to rename your "Array" class, for example to "MyArray"
And i suppose there are some troubles with Array class constructor.
Try to copy initialArray in to your local variable.
public class MyArray {
int[][] localArray;
public MyArray(int[][] initialArray) {
localArray = initialArray.clone();
for (int i = 0; i < initialArray.length; i++) {
localArray[i] = initialArray[i].clone();
}
}
public String toString() {
// ...
}
}
I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!
I am very new to Java and writing this program to shuffle words and fix the suffle words. The following is my program. After I call mix(), I would like to be able to assign the output of word to team array within main.
For some reason, I can call mix() it works but I cannot access word which is in the shuffle function. Since I am in main and all these function within main, I thought I can access the variables. Any ideas what I am missing here?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2
{
public static void main(String[] args)
{
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan= new Scanner(System.in);
input = scan.nextInt();
//System.out.println(input);
if(input==1) {
mix();
System.out.println(word);
char team[]=word.toCharArray();
for(int i=0;i<team.length;i++){
System.out.println("Data at ["+i+"]="+team[i]);
}
}
else{
System.out.println("this is exit");
}
}
static void mix()
{
String [] lines=new String[1000];//Enough lines.
int counter=0;
try{
File file = new File("input.txt");//The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag=true;
while(true){
try{
lines[counter]=buffer.readLine();//Store a line in the array.
if(lines[counter]==null){//If there isn't any more lines.
buffer.close();
fileReader1.close();
break;//Stop reading and close the readers.
}
//number of lines in the file
//lines is the array that holds the line info
counter++;
}catch(Exception ex){
break;
}
}
}catch(FileNotFoundException ex){
System.out.println("File not found.");
}catch(IOException ex){
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter ) + 0;
System.out.println(lines[pick]);
///scramble the word
shuffle(lines[pick]);
}
static void shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
String word=output.toString();
}
}
Return string value from shuffle() method using return statement:
static String shuffle(String input) {
// . . .
return output.toString();
}
...and then use it in mix:
String word = shuffle(lines[pick]);
But it is better to read basic java tutorials before programming.
In Java, variables cannot be seen outside of the method they are initialized in. For example, if I declare int foo = 3; in main, and then I try to access foo from another method, it won't work. From the point of view of another method, foo does not even exist!
The way to pass variable between methods is with the return <variable> statement. Once the program reaches a return statement, the method will quit, and the value after the return (perhaps foo) will be returned to the caller method. However, you must say that the method returns a variable (and say what type is is) when you declare that method (just like you need to say void when the method does not return anything!).
public static void main(String[] args){
int foo = 2;
double(foo); //This will double foo, but the new doubled value will not be accessible
int twoFoo = double(foo); //Now the doubled value of foo is returned and assigned to the variable twoFoo
}
private static int double(int foo){//Notice the 'int' after 'static'. This tells the program that method double returns an int.
//Also, even though this variable is named foo, it is not the same foo
return foo*2;
}
Alternatively, you could use instance variable to have variables that are accessible by all the methods in your class, but if you're new to Java, you should probably avoid these until you start learning the basics of object-oriented programming.
Hope this helps!
-BritKnight