So i have been at this same example problem for a week now. I know that it may
seem easy, but i am finding that the more i look at it or alter it, the more
confused i get. I feel like i am making this a lot more difficult than it
needs to be. The array that i loaded displays correctly in the Try-Catch section, but i need to display it in its own method, which i call listOfAges(). What would this look like? Any responses are appreciated, please help.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray;
int ageCount = 0;
int age;
String filename = "ageData.dat";
anArray = new int[50];
/* The file has 50 numbers which represent an employee's age */
try {
Scanner infile = new Scanner(new FileInputStream(filename));
while (infile.hasNext()) {
age = infile.nextInt();
ageCount += 1;
System.out.println(ageCount + ". " + age + "\n");
/*
* When i run just this, the output is correct...
*
* But i don't want the output here, i just want to gather
* the information from the file and place it at the bottom inside
* the method displayAges().*/
}
infile.close();
} catch (IOException ex) {
ageCount = -1;
ex.printStackTrace();
}
public void listOfAges() {
System.out.print(" I want to display the data gathered from ageData.dat in this method ");
System.out.print(" Also, i receive this error message when i try: 'Illegal modifier for parameter listOfAges; only final is permitted' ")
}
}
}
First, you have to store your values in your array:
while (infile.hasNext()) {
age = infile.nextInt();
anArray[ageCount] = age;
ageCount += 1;
}
Your next problem is that you defined your listOfAges() method inside your main() method. The definition must be outside. You also need to pass your array as an argument to your method so that you can iterate over the array values to print them:
public void listOfAges(int[] ages) {
// use a loop here to print all your array contents
}
So I'm assuming you want to display each element in the array in your method. Your first problem is that the main method is static and you're trying to call a method that isn't static (listOfAges). Change this by simply adding the word static to the method to make it static. You also put this method in the main method. You'll need to move it outside of the brackets.
Second, to display the content you need to loop through it but the array you're holding the data in needs to be outside of the main method. Instead of having
int[] anArray;
In the main method, delete that and move it above the declaration of the main method. You'll also need to make it a static variable.
static int[] anArray;
Finally in the listOfAges, add the code to loop through it.
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray.length + ". " + anArray[i]);
}
I'm not 100% sure what you're asking but here:
At
} infile.close(); } catch (IOException ex) { ageCount = -1; ex.printStackTrace(); }
In your While.infile loop you're closing your while loop on the } infile.close() instead of opening a new one. So just change it to { infile.close (); } instead...
Since I'm not sure what you're exactly asking this will be the best answer I can give youx , hope I helped.
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I'm am very much a rookie when it comes to coding. What I'm trying to accomplish is to load grades from a txt file and put them into an existing array.
I have actually solved this. and In the program the array does retain the values. But when I got to print them I get the object reference aka [I#5c647e05 rather than the array. Below is my code.
public static void main(String[] args) {
int[] list = new int[15];
Scanner in = null; // create a scanner object
loadGrades(in, list);
System.out.println(list);
}
public static void loadGrades(Scanner in, int[] list) {
int grades; // int variable
try { // try
in = new Scanner(new FileReader("Proj5Data.txt"));// change filename
} catch (FileNotFoundException ex) { // catch
System.out.println("File not found");
System.exit(1);
}
for (int i = 0; i < list.length; i++) {
grades = in.nextInt(); // var
list[i] = grades ;// put the int in the array at the counter value
}
in.close();
}
Print results as:
[I#5c647e05
BUILD SUCCESSFUL (total time: 0 seconds)
When you print an array behind the scenes the method toString() is being called and it doesn't print the content of the array (which is too bad IMO). But you can easily get over it using the library Arrays:
System.out.println(Arrays.toString(list));
You can't print the contents of a list like that in Java. You need to loop over the contents of the array and print them individually.
for(int i : list){
System.out.println(i);
}
System.out.println(list) uses a .toString() method to resolve what to print.
You can either use Arrays.toString(list) or print it one by one.
So All the methods you guys gave me did indeed work. But I ended up just using printf to print them out. Thanks for the help though.
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'm having a difficult time figuring how to display the shared personArray with the appropriate course object. For example, I need to display a list of a course and the people that are in that course, and again for the next course. I feel that there's something wrong with my nested for loop or the personCount variable because not every course has the same amount of people so how do I deal with this?
Hopefully you all can get a clear picture of the stripped down code below.
Note* I must use aggregation and toStrings, and not allowed to use lists, arraylists, or scanner.
Thanks!
public class School {
private static Course[] courseArray = new Course[5];
public static void printList(){
String print = "";
for (int x = 0; x < courseCount; x++) {
print += courseArray[x].getCourseName() + "\n";
for (int y = 0; y < personCount; y++){
print += courseArray[y].personArray[y].getPersonName()+ "\n";
//^ I thought I could use the 1st forloop index to stay in the 1 course and print out all the people for that course(like the hardcode example below) but I get a nullpointer
}
}
JOptionPane.showMessageDialog(null,print);
/*
If I hardcode the print String like below I get the correct output.
So I know my objects are being stored properly, but I can't figure out how to get the correct display with a loop
print += courseArray[0].personArray[0].getPersonName(); //tim (bio)
print += courseArray[0].peopleArray[1].getPersonName(); //bob (bio)
print += courseArray[1].peopleArray[2].getPersonName(); //john (art)
*/
}
}
------------------------
public class Course {
private Person[] personArray = new Person[50];
//constructor for course
// get/set courseName methods
public String toString(){
// not sure how to use this the right way
}
}
-----------------------------------
public class Person extends Course {
//constructor for person
// get/set personName methods
public String toString(){
return getPersonName();
}
}
Make sure that all 50 of the people in your personArray are initialized first; check to see if they are by printing out the entire array like so (you will need to import java.util.Arrays):
System.out.println(Arrays.toString(course[x].personArray));
If that gives back any "null" values then you know that not every single Person in the PersonArray was initialized first.
You should change courseCount to courseArray.length and personCount to courseArray.getPersonArraySize() and implement getPersonArraySize() in Course class to return length of personArray.
replace your loops with these below..
for (Course c : courseArray) {
print += c.getCourseName() + "\n";
for (Person p : c.personArray){
print += p.getPersonName()+ "\n";
}
}
I'm having trouble with calling a method. The basis of the program is to read in data from data.txt, grab the name token given, then all of the grades that follow, then implement some operations on the grades to give details of the person's grades. I do all of the methods in a separate file named Grades.java, which has the Grades class. I'm just having trouble because I MUST have the testGrades method in my code (which I don't find necessary). I have done everything I need to do for the results to be perfect in a different program without having two different .java files. But it's necessary to do it this way. I think I have mostly everything pinned down, I'm just confused on how to implement and call the testGrades method. I commented it out and have the question on where it is in the program. Quite new to classes and objects, and java in general. Sorry for the lame question.
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
//testGrades(sgrades); How would I implement this method call?
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
}
}
This is a little snippet of the beginning of the Grades.java file
public class Grades {
private String studentName; // name of student Grades represents
private int[] grades; // array of student grades
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
}
public String getName() {
return studentName;
} // end method getName
public int length() {
return grades.length;
}
well your test grades take a Grades object so you need to construct a Grades object using your data and pass it to your test grades method
i.e.
Grades myGrade = new Grades(studentName,sgrades);
testGrades(myGrade);
It looks like what you need to do is have some type of local variable in your main method, that would hold your custom Grade type. So you need add a line like..
Grades myGrades = new Grades(studentName, sgrades);
Then you can call your testGrades method with a line like...
testGrades(myGrades);
Looks like you may also need a toString method in your Grades class.
Seems like homework, so I tried to leave a bit to for you to figure out :)
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