Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm not exactly new to programming, but for some reason I cannot get past this issue. I'm writing a method, and keep getting the "reached end of file while parsing" compiler error. Normally this happens when you forget a }, but this method only has two sets of brackets, and I'm not missing either close. Could anyone point out why I'm getting this error?
public class Locations{
//member variables
static int totalNumberOfRooms = 0;
int numberOfExits;
//pointers to each exit
String roomGeneralDescription;
String roomDescription;
//member methods
String getRoomGeneralDescription(){
return this.roomGeneralDescription;
}
String getRoomDescription(){
return this.roomDescription;
}
//constructor to more easily create objects
public Locations(int exit, String description, String generalDescription){
totalNumberOfRooms += 1;
numberOfExits = exit;
roomDescription = description;
roomGeneralDescription = generalDescription;
}
//default constuctor
public Locations(){
totalNumberOfRooms += 1;
}
//generates the given number of Locations obejcts, with pointers stored in a returned
//array.
Locations[] createLocations(int x){
int iterate = 1;
int loopMax = x;
Locations[] arrayOfLocations = new Locations[x -1];
while (iterate <= loopMax){
int index = iterate -1;
arrayOfLocations[index] = new Locations();
iterate += 1;
}
return arrayOfLocations;
}
You are missing a closing brace } at the end of your file.
Locations[] createLocations(int x){
int iterate = 1;
int loopMax = x;
Locations[] arrayOfLocations = new Locations[x -1];
while (iterate <= loopMax){
int index = iterate -1;
arrayOfLocations[index] = new Locations();
iterate += 1;
}
return arrayOfLocations;
}
} // YOU NEED TO ADD A CLOSING BRACE TO FINALIZE THE CLASS DEFINITION
Update: Even though the closing brace was the solution, I couldn't help but notice at how your createLocations method is actually written. It's an odd way to do an array allocation. I'm not even sure what you have will run without crashing because the array is allocated to be of size [x-1]. In any case, here's a more clean solution to creating an array in Java. I hope this helps!
Locations [] createLocations(int count) {
Locations [] arrayOfLocations = new Locations[count];
for (int i = 0; i < count; i++) {
arrayOfLocations[i] = new Locations();
}
return arrayOfLocations;
}
} // YOU NEED TO ADD A CLOSING BRACE TO FINALIZE THE CLASS DEFINITION
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I have to apply linear scan to this problem, and I just don't even know where to start. I feel as if I should change my career path honestly, this is a simple intro problem and i'm just not understanding anything about it.
/**
* Applies the linear scan strategy to counting the number of negative
* values in an array.
*/
public class CountNegatives {
/**
* Returns the number of negative values in the given array.
*/
public static int countNegatives(int[]a) {
neg=0;
for{i=0;i<a.length;i++}
if(i>0)
neg = neg+1;
return neg;
}
}
I've tried running this in VS and a tool my school uses called JGrasp. Both told me the { should be ( , the ; between length and i should be > , i<a.length is not a statement, and that } should be ;
When I change any of these things, it tells me variable neg=0 cannot be found and doubles the amount of errors in the code.
There are a few things you missed,
You did not initialize the neg=0; value with the proper data type; you should initialize it with the proper data type, which int his case is int, correct initialization would be int neg = 0;
the other problem would be in the for loop you still need to initialize i with a data type
the if statement is wrong, it should be 'i<0' instead cause with your code you are just counting the positive values
You are comparing the index value with 0 so you won't get the right value, instead, you should compare the value in the array that corresponds to that index, you can do this by arrayName[index].
The correct code would be as follows:
static int countNegatives(int[] a) {
int neg = 0;
for(int i = 0; i < a.length; i++) {
if(a[i] < 0) neg++;
// this will just work as neg = neg +1;
}
return neg;
}
}
public class CountNegatives {
/**
* Returns the number of negative values in the given array.
*/
public static int countNegatives(int[]a) {
int neg=0;
for(int number : a){
if(number<0) {
neg=neg+1;
}
}
return neg;
}
}
Hey I am a high school and I found the solution to my problem but confused on why it's doing what it's doing can someone explain? Also I tried looking for the answer but couldn't find it so sorry if someone's already answered this.
So at getAverage() I state int i; and initialize it in the foreach loop but when it runs it says "variable i might not have been initialized"? I found the solution to this was just make int i = 0; but i'm confused because I know you can state a variable and not initialize it at that time as long as you initialize it later. So what makes this so special?
public class ArrayAverage
{
private int[] values;
public ArrayAverage(int[] theValues)
{
values = theValues;
}
public double getAverage()
{
// Problem here
int i; // Solution: int i = 0;
for(int value : values){
i += value;
}
double avg = (double)i / values.length;
return avg;
}
}
// This pseudo code code has nothing to do with above code
// but is example of what I know can be done but isn't
int i;
i = 10;
System.out.println(i);
//Output would be 10
The issue is that the you're adding the variable i to itself, and another value. However, the initial value for i has not been defined in the previous code. This is the reason that i = 0 would make the code work, as the program now understands that for the first loop, it has to add the value to 0, then the second loop will know to add the previous value, to the new value.
Hope this helped.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
Good Afternoon, I have a final project to do and need some help. I would just like to grasp the algorithm of sorting a 1d array of objects from a file. I know how to do it with a regular array using a counter in a for loop or a for each loop. I'm having difficulty reproducing it with with my objects. Thanks in advance.
public static void printFile()throws IOException {
File f = new File("program7b.txt");
Scanner in = new Scanner(f);
int count = 0;
Customer[] obj = new Customer[in.nextInt()];
while(in.hasNext() ){
int id = in.nextInt();
String name = in.next();
String email = in.next();
double balance = in.nextDouble();
in.nextLine();
obj[count] = new Customer (id, name, email, balance);
count++;
}
in.close();
for (int i = 0; i < count; i++){
System.out.println(obj[i]);
if (obj[i] instanceof TaxExempt){
System.out.println("Tax Type: " + ((TaxExempt)obj[i]).getExempt());
}
}
}
public static void sortCust(Customer[] id){
int temp = 0;
for (int i = 1; i < id.length-1; i++){
}
}
In my experience, you would use a compareTo method in the class of the object. Since objects can have multiple instance variables and other objects within them, you have to pick a specific field to sort on.
Say you have an object (Account) with a person's name and bank balance. You would want to sort by bank balance.
public int compareTo(Account a){
if(balance<a.getBalance())
return -1;
if(balance==a.getBalance())
return 0;
else
return 1;
}
Now that you have a compare to, you can bubble sort/quick sort/selection sort (I barely even know what those mean anymore), just like you would with an array of ints.
The biggest difference is that your condition will specify object.compareTo(otherObject) and will be based on if it is <0, ==0, or >0.
Be careful when you are moving objects though. You want to make sure to do a deep copy of all the details in the objects, not just copy the objects. For this reason, I recommend a swap method and a copy method.
Good Luck!
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Sometime when we declare and initialize a variable, say we have an int i =10; then after some code this variable would be modified like this code bellow
public class reset {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 10;
int co = 1;
while (co < 10) {
i++;
System.out.println(i + "*" + co + "=" + i * co);
if (i == 99) {
i = 11; //line 11
co++;
}
}
}
}
then at some point (here at line 11) we need to re-initialize then variable, wouldn't it be nice if we had any language feature doing it automatically instead for example
reset:i
I think it's very beneficial for productivity, isn't it?
we need to re-initialize then variable, wouldn't it be nice if we had any language feature doing it automatically instead?
No
I think it's very beneficial for productivity, isn't it?
No
Resetting a variable to its start value is in many cases a sign that the scope of the variable is to large. So with clean code you hardly ever need such feature.
And of course every feature comes at the cost of complicating the language even more.
The initializer line
int i = 10;
simply creates byte code instructions to assign the value 10 to the variable. That assignment is no different than any other assignment.
To implement reset, there would need to be an extra bit of metadata kept for each variable to say what the special, initial value is.. That metadata is not currently kept in the symbol table, since there is no concept in Java for a 'initial value'. The additional overhead would trade off against the utility of the reset command.
Might be a good idea, but you can get the same thing by just declaring a constant, and reassigning to the constant.
What about this code? I can understand your question from a starter's perspective, but usually it requires a bit more practice to see why certain constructs are not required:
public class NoReset {
private static final int X_START = 11;
private static final int X_END = 99;
private static final int Y_START = 1;
private static final int Y_END = 9;
public static void main(String[] args) {
for (int y = Y_START; y <= Y_END; y++) {
for (int x = X_START; x <= X_END; x++) {
final int result = x * y;
System.out.printf("%d * %d = %d%n", x, y, result);
}
}
}
}
Note that you should not nest to many loops, but creating a "hidden loop" is at least as dangerous, it gets very hard to track variables such as i within your code.
If you want to use the current Java language to do what you want to do, then simply provide a function in each class that you want to perform a "reset" like:
private void reset() {
var = xxx;
var2 = yyy;
...
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm stuck trying to figure out how to loop through an array of zip codes and find the closest zip code to a target. The zip codes also contain their latitude and longitude which is used to calculate the distance to the target. I need figure out how to loop through the array storing the closest distance and then returning the zip code of the closest one. Any help would be great because I've tried everything I can think of.
* Finds and returns the zip code of a postal zone in the collection
* whose centroid is closest to a given location.
*
* #param target the target location.
*
* #return returns zipCode of the postal zone whose centroid is closest;
* returns COLLECTION_EMPTY if no zones are in the collection.
*/
public String findClosestZone(Location target)
{
int counter = 0;
String closeZip = COLLECTION_EMPTY;
double closestDistance = 100.0;
for (int i = 0; i < this.zoneCount; i++)
{
if (this.zones[i].getZoneLocation()
.calcDistance(target) < closestDistance)
{
closeZip = this.zones[i].getZoneZipCode();
closestDistance = this.zones[i]
.getZoneLocation().calcDistance(target);
counter++;
return closeZip;
}
}
return closeZip;
}
According to doc:
A method returns to the code that invoked it when it
1. completes all the statements in the method,
2. reaches a return statement, or
3. throws an exception,
whichever occurs first.
It means that your code finishes its work after the first iteration. As far as I understand you want to find the closest one among array of zones.
I guess you don't need return inside loop. Please comment or delete it .
public String findClosestZone(Location target)
{
int counter = 0;
String closeZip = COLLECTION_EMPTY;
double closestDistance = 100.0;
for (int i = 0; i < this.zoneCount; i++)
{
if (this.zones[i].getZoneLocation().calcDistance(target) < closestDistance)
{
closeZip = this.zones[i].getZoneZipCode();
closestDistance = this.zones[i].getZoneLocation().calcDistance(target);
counter++;
// return closeZip;
}
}
return closeZip;
}