Can't access my array - java

My programme is to create a Train Route Finder using Java, first off as a command line programme then convert into a GUI. That's the least of my worries for now. I am currently stuck on one functionality of my system and that is to display the list of stops between two stations that the user previously input.
Now, I have been able to prompt the user to choose their stops (lines 3,149 - 3,171 in my code):
if(deptChoice == 1 && arrChoice == 2){
List<String> stopList1_2 = new ArrayList<String>();
Scanner stopPick = new Scanner(System.in);
stopPick.useDelimiter(System.getProperty("line.separator"));
do {
System.out.println("\nCurrent list of stops between Leicester to Loughborough is:\n\n" + stopList1_2);
System.out.println("\nWould you like to add a new stop? (Please enter 'Yes' or 'No')\n");
if (stopPick.next().startsWith("Yes")) {
System.out.println("\nPlease type in the stop you wish to add to the route:\n");
stopList1_2.add(stopPick.next());
}
else {
break;
}
} while (true);
String[] stopArr1_2 = stopList1_2.toArray(new String[0]);
System.out.println("\nCurrent stops between Leicester to Loughborough is:\n\n" + Arrays.toString(stopArr1_2));
}
and the stops they type in are added to an array. When they are satisfied with the amount stops between the stations there are then the loop ends and it displays the array of stops between Station X and Station Y.
However, here comes the problem:
I want to then gain access to this previously created array with all the exact stops further up my code. In this "if" statement, if it is satisfied, then I want the array (stopArr1_2) to be displayed (in lines 3,019 - 3,021):
if(deptChoice == 1 && arrChoice == 2){
System.out.println(""); //this should be where I call the array back to display itself
}
as those stops would correspond with the users choice of deptChoice == 1 (Station 1 = Leicester) to arrChoice == 2 (Station 2 = Loughborough).
I hope this is clear:
I basically want the array of stops inputted by the user to reappear when they choose Train Routes.
Here his my full code I made in Notepad++ I thought it would be better for you lot to see all of my code rather than small segments and it is commented.
Furthermore, to comprehend my problem run my programme. To understand my problem do this:
1) Compile Train.java (javac Train.java)
2) Run programme (java Train)
3) Pick Admin Menu (Number 5)
4) Pick Input Menu (Number 1)
5) Pick any two stations
6) Enter a couple of stops until you're happy
7) When it shows the final stops array for those two stations the programme seems to end so hopefully that is not an issue
8) Run programme again (java Train)
9) Pick Train Routes (Number 3)
10) Pick the SAME stations in the same order as you did before so it would find the array you just made
11) Now nothing will come up because, well, that's my problem. I don't know how to regain that array I just made for it.
Download link to my Train.java file (and Train.txt file if needed):
https://www.dropbox.com/s/7dy0pp9vyykwhrk/TrainJava.rar
Any suggestions?

Whats the location of your second block of code ? ( The code where you said you need access to the List<String> stopList1_2 ) ?
1 If its in the same class but in a different method , then
Move this declaration
List<String> stopList1_2 = new ArrayList<String>(); ( currently in your first block of code ) to a class field.
BUT
2 If its in the same class and also in the same method as your first block of code, then
Move this declaration
List<String> stopList1_2 = new ArrayList<String>(); ( currently within the if statement of code ) to outside the if condition .
but treat this as a quick recipe for you problem at hand. More importantly - please read the variable scoping rule and access specifiers in java.

Related

How can I get my output to only display a certain message when the users input is not 1 of 2 certain strings (options)?

my code
I'm pretty much brand new to java and coding been practicing for a couple weeks now and I'm trying to figure out how to get my output to only display the else statement when NONE of the 2 'if' options have been inputted.
for ex. i have 2 categories of food places, Mexican and American. When the user is prompted to enter a category it displays the array of restaurants just fine but I cant get the else statement to not pop up with the first if option. No matter what if the first 'if' option is inputted the else statement gets printed, how do i stop that and only have it print when 'American' or 'Mexican' isn't inputted.
This "else" referrers to second "if". Use "switch-case" construction instead with "else" value as default.
You should use an if-elseif-else block instead of if ... if-else. That's the issue.
if (/* code for mexican */) {
System.out.println("mexican options...");
} else if (/* code for american */) {
System.out.println("american options...");
} else {
System.out.println("Sorry, no options available");
}

How to check if the input given by the user is Y or N

to summarise it give me any idea or solution on how I could fix it.
I tried what is given in the code below.
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end =="Y")
System.out.println("hello");
I expect the output hello in the above code, but the actual results are nothing the program just ends.
First of all, I have no idea what your question is about exactly. I can't see any information on which programming language you are using (I suppose Java) or on which operating system you are working.
But I've got an idea what the problem might be: As you are using stdout, I suppose the program happens on a Console or Terminal. And in some environments, the cmd window will close after there program terminated (when working with an IDE like VS Community, which I don't know if you do or not, given no context). If this is the case, "hello" will be printed but you won't see it because the window closes immediately. Try to add some kind of getline at the end and try again.
Supposing sc is a Scanner object.
String comparison must be done with the equal method instead of using == because by doing that you'll compare the object's referer in the memory instead of the String content, try this:
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end.equals("Y")) {
System.out.println("hello");
}

Check input continuously on one line?

I am trying to make a simple code which continously checks the user input on if the number is positive or negative and that it would all be on 2 lines.
First line being the user input and the second line being the output.
I am a beginner in coding and am not such a professional, but I have right now put the Scanner object in a while loop and it checks if the user input is positive. If it's negative then it would stop the program.
import java.util.Scanner;
public class basic {
public static void main(String[] args){
int numb;
Scanner scanner = new Scanner(System.in);
System.out.println("Fill in a random number which ain't negative!");
while((numb = scanner.nextInt()) > 0) {
System.out.println("Again!");
}
{
System.out.println("This is a negative!");
System.exit(1);
}
}
}
What I want to do is that I get this as an output and only on 2 lines:
1 2 3 4 5
Again!
And if I input a negative number on the line that it changes the 'Again!' to 'This is a negative!'
1 2 3 4 5 6 -8
This is a negative!
But with the code I have now I can only get this as an output and would get much more than just 2 lines:
1
Again!
2
Again!
-3
This is a negative!
This is console output so cannot be overwritten.
But if you are really looking to the getting required o/p printed on the console, you can use list and keep pushing digits to it and print all the items of the list.
You could use \r to rewrite the last line. Consider that:
System.out.println("\r"+yourOutput+" > ")
It replaces the last line in the console with this one, that's how loading bars in linux are done by the way :D. Use this method to display your previous inputs/numbers. User input will be in the second line. When user has pressed enter and your program has gotten the user input as string, process it and do the same thing again, this time with yourOutput updated with new info:
System.out.println("\r"+yourOutput+" > ")
Let me welcome you to your first post on StackOverflow!
It is unusual to have java applications clearing the console output. That being said, it is possible, but not without calling OS commands. As mentioned in comments, this is a little beyond beginner material if you do this.
If you want to try it though, as seen here, you can clear the console by executing a native OS command. If you use the below code (copied from the link with a minor edit)
public static void clrscr(){
//Clears Screen in java
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (Exception e) {}
}
you can call this with clrscr() in your code and you should be able to clear the screen.
Now looking at your code, you won't just be able to slip this in as you will clear the output, thus clearing the past numbers. If you want it the way that you described where you have all the user's output displayed in succession, you'll need to re-print all their entries each time you clear the screen. Thus each time you get a user's input:
You'll want to take that input and add it to a list of numbers
Clear the screen
Output that entire list
Output your evaluation
Let me know if you have questions. :-)

Last iteration of for loop not outputting

Forgive me if this is not formatted properly, this is my first post. I looked to see if this issue has been found before and I cannot find anyone who has had the same problem I am having.
I am trying to learn Java and cannot for the life of me figure out why my for loops are not outputting the last iteration. I am going through codeabbey's exercises and completed the first two relatively easily. However on the third and fourth problems, I cant get my for loop to output during the last iteration.
I began looking on google and thought I would compare my answer to someone else's. I couldn't see why mine wouldn't work when my code was almost identical to the person I found. So I copied their code and to my surprise I had the same problem when this code also would not output on the last iteration.
So, here is the context.
The website gives you a single number first which is the number of sets of the following numbers. For the third problem, you are to add the sets of two, output the sum followed by a space and loop through the entire batch. For the fourth problem, it is similar where the first number is the number of sets in the batch but you are to compare the two numbers and output the lower number. I will copy my code here for the third problem because the code is simpler.
Here is the code:
import java.util.Scanner;
public class Summation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n;i++){
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b + " ");
}
}
}
Here is the input you are to copy and paste:
3
100 8
15 245
1945 54
and this is my output:
108 260
So, as you can see we are missing the last output here. I tried changing the for loop to (i < (n+1) ) which still didn't change anything. Any help would be GREATLY appreciated!
Ok so I tested it, and with your numbers, typing them in one by one it works. Copy pasting them, press enter one more time at the end of the copy. If you don't press enter, the scanner thinks you're still adding to the second number so it won't continue until enter is pressed.
I would try using println() as someone else suggested, or calling flush() at the end of the program to make sure something isn't being held in a buffer and not being written.

Java - farkle (greed) game (die and player arrays, multiple classes)

I am trying to write code for a command like game of Farkle (greed). This is an Intro to computer science class. In a nutshell, you roll 6 die, and scores are based off of what you roll. Then you are required to remove the die that were used -> display score from that roll -> display total score -> ask if they would like to roll again. First player to a score determined by the user is the winner.
I have a bunch of code written for the model, and I am working on the view. I am struggling with the view, which makes it harder to advance on my model code. We are required to use the Die and Player classes (we were given those). I use the Die quickly, not quite sure how to apply the Player class.
When I try to run my command line, I am getting out of bounds errors on my rollCheck() array and other issues in my model that were not coming up when I simply was testing in main. I apologize for the amount of code posted, but I figure seeing everything makes it easier to solve (goes without saying really).
If anyone can give me pushes in the right direction to solving and making my program work, that would be great! Thank you.
Without being able to run the program to be sure its hard to be certain (I need the top of GreedGame) but i'd be fairly confident its the following:
in rollDie die is set to an array of ints on size remainingDie
this.die = new int [remainingDie];
later, within rollCheck the contents of the die array up to and including remainingDie, going over the array by 1
for (int i = 0; i <= remainingDie; i++) { // Count up quantity of die (6 set to remaining die)
if (die[i] == 1) {
this.numFreq[0] += 1;
}
....
....
}
So in short I believe i <= remainingDie; should be i < remainingDie; because an array with 6 entries has "boxes" 0,1,2,3,4,5

Categories

Resources