简体   繁体   中英

How to access a string value in a while loop, outside of a while loop, all while inside a method

The program itself is supposed to take user input and then read it off in the setup of how a Mad Lib is made. The user types in a noun, verb, adjective, etc, and then its all printed to the console in the form of a story.

import java.util.Scanner;

public class CSFacts {

    //first method
    public static String Noun(int on)   {           //Start first user input, start with noun
        String noun1;
        Scanner input=new Scanner(System.in);
            while (on==1)   {
                System.out.println("Please enter a Noun.");     //prompt user to input a noun to be used in the main program
                noun1=input.nextLine(); 
                on=on-1;}
            while (on==0)   {
                noun1=input.nextLine(); }
            return noun1;
        //return the noun as a string to be used in the main program
    }
    public static void main(String[] args)  {
        Noun(1);
        System.out.println("Be kind to your "+Noun(0));
    }

The problem that I'm facing is that noun1 wont cooperate with me in the aspect of it will not carry though from one parameter to the other. I need noun1 to carry from on=1 to on=0 so that when the method is called for a second time it reads "Be kind to your (insert noun1)". I cant seem to figure out how to carry it over. This is only a section of my lab, but if I can figure out how to do this, I can implicate it into my other methods.

You seem to have an infinite loop:

while (on==0)   {
    noun1=input.nextLine(); }

You call your method with Noun(1) , so on is 1. Your first loop will run once, then end, setting on to 0. Your second loop will then run forever because it never changes on , but keeps going until it gets changed, which will never happen.

To answer your actual question, noun1 is defined inside the method Noun() , so it's a local variable and can't be used anywhere else. To fix that, you could define it as a static variable outside of Noun() like this:

static String noun1;

Another option would just be to use the value returned from Noun() inside your main method, instead of discarding it, like you're doing:

String noun1 = Noun(1);

There seems to be confusion in the control flow of your program. Remember that your program is a sequence of instructions . If you trace your control flow carefully, step by step, you will discover some problems. I will help detail what your program does and I will leave it to you to reason about it.

public static void main(String[] args)  {
    Noun(1);                                         // (0)
    System.out.println("Be kind to your "+Noun(0));  // (1)
}

I have added comments to label each statement. Your program always starts in the main method and on the first statement. Here is what main does.

  • (0) call Noun with on = 1 , goto (1)
  • (1)
    • call Noun with on = 0 , store result in tmp1
    • append the string stored in tmp1 to "Be kind to your ", store in tmp1
    • print the string stored in tmp1

I added extra detail to (1) and invented the variable name tmp1 to ease the explanation — your program will store the data somewhere.

It is important to note that calling a function yields control to that function. This means the caller does not execute its next statement until the callee has executed all of its statements.

public static String Noun(int on)   {
    String noun1;                                   // (0)
    Scanner input = new Scanner(System.in);         // (1)
    while (on == 1) {                               // (2)
        System.out.println("Please enter a Noun."); // (3)
        noun1 = input.nextLine();                   // (4)
        on = on - 1;                                // (5)
    }
    while (on == 0) {                               // (6)
        noun1 = input.nextLine();                   // (7)
    }
    return noun1;                                   // (8)
}

Here is what the Noun function does.

  • (0) initialize noun1 to null , goto (1)
  • (1) construct a new Scanner object and store in input , goto (2)
  • (2) if on == 1 goto (3) else goto (6)
  • (3) print "Please enter a Noun.", goto (4)
  • (4) read a line of input and store into noun1 , goto (5)
  • (5) store on - 1 into on , goto (2)
  • (6) if on == 0 goto (7) else goto (8)
  • (7) read a line of input and store into noun1 , goto (6)
  • (8) halt and return the value of noun1

Notice there are a few problems just considering Noun by itself. I will focus on just one to help you get started.

If on is not equal to 0 or 1 then Noun will return null , which is why your IDE warns you. Why? To answer that, we just have to assume the hypothetical situation that on is neither 0 nor 1 and then manually execute the Noun function.

For simplicity I will choose on to be 3. I will keep track of the state of all variables as the function executes. To the left of the state I will indicate which statement I am executing, which I have decided only by following the program.

  1. (0) on = 3, noun1 = null
  2. (1) on = 3, noun1 = null, input = new Scanner(System.in)
  3. (2) going to (6) because on is not equal to 1 on = 3, noun1 = null, input = new Scanner(System.in)
  4. (6) going to (8) because on is not equal to 0 on = 3, noun1 = null, input = new Scanner(System.in)
  5. (8) halting and returning value of noun1 on = 3, noun1 = null, input = new Scanner(System.in)

I suspect there is also confusion with variable scope . This indicates the lifetime of the variable. I will just briefly mention that variables declared in a function are destroyed (go out of scope) when the function halts (returns a value or throws an exception).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM