How to create variable across entire java class? - java

I have a method that asks for the user's name, then returns it. Now I want to access the user's name in another method, but when I print the user's name it says "null". I don't understand, I defined the variable, but how can I give it access across the entire class?
public static String userName() {
Scanner input = new Scanner (System.in);
System.out.print("Hello! Welcome to The Game. Whats your name? ");
String userName = input.next();
return userName;
}
This is the method where I try to access the userName variable but am given "null"
public static void homeMethod() {
Scanner input = new Scanner (System.in);
System.out.println("Hello " + userName + "! What would you like to do? (Type LIST for options)");
String userGameChoice = input.nextLine();
}
Calling the userName() method inside the homeMethod() i am given the same error.
Any help is much appreciated. Thanks!

I needed to create userName variable outside of the method.
This is what I had:
public class MainGameClass {
public static String userName;
public static String userName() {
Scanner input = new Scanner (System.in);
System.out.print("Hello! Welcome to The Game. Whats your name? ");
String userName = input.next();
return userName;
}
public static void homeMethod() {
Scanner input = new Scanner (System.in);
System.out.println("What would you like to do " + userName + "? (Type LIST for options)");
String userGameChoice = input.nextLine();
}
}
Output when calling homeMethod():
What would you like to do null? (Type LIST for options)
Solution:
public class MainGameClass {
public static String userName;
public static String userName() {
Scanner input = new Scanner (System.in);
System.out.print("Hello! Welcome to The Game. Whats your name? ");
String userName = input.next();
return userName;
}
public static void homeMethod() {
Scanner input = new Scanner (System.in);
System.out.println("What would you like to do " + userName + "? (Type LIST for options)");
userGameChoice = input.nextLine();
}
}
Output when calling homeMethod():
What would you like to do (userName)? (Type LIST for options)
Explanation:
I correctly defined the userName variable in the class, however, in the userName() method, I created a new variable under the same name. Therefore not returning the answer to the userName variable.

Either declare userName variable outside the method, in the class itself or call userName method in your homeMethod like this:
public static void homeMethod() {
Scanner input = new Scanner (System.in);
System.out.println("Hello " + userName() + "! What would you like to do? (Type LIST for options)");
String userGameChoice = input.nextLine();
}

You have to put userName out of the method like this:
System.out.print("Hello! Welcome to The Game. Whats your name? ");
String userName = input.next()
public static String userName() {
Scanner input = new Scanner (System.in);
return userName;
}

Related

I have an error saying, syntax error on tokens, delete these tokens and many more, you can see for yourself

It says on the line String correctname="Pisay"; syntax error delete this token
package StringExple;
import java.util.Scanner;
public class StringExple{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String correctname=”Pisay";
System.out.println(“Enter your username:”);
String username = sc.nextLine();
if(username.equals(correctname)){
System.out.println(“Authorized user!!”);
} else
System.out.println(“Unauthorized user!!”);
if(username.equalsIgnoreCase(correctname)) {
System.out.println(“Authorized user!!”);
} else
System.out.println(“Unauthorized user!!”);
}
}
Couple of syntax issue is there, after fixing working.
Say Double Quotes " in print statements are not proper.
It's simple syntax issue if you concentrate then you should be able to fix them by own.
As you are doing 2 tests for both equals() and equalsIgnoreCase(), you may verify using equalsIgnoreCase() only because it will include equals() check also.
package sep2020;
import java.util.Scanner;
public class StringExple {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String correctname = "Pisay"; // String input
System.out.println("Enter your username:");
String username = sc.nextLine();
if (username.equalsIgnoreCase(correctname)) {
System.out.println("Authorized user!!");
} else
System.out.println("Unauthorized user!!");
}
}
Output:
Enter your username:
test
Unauthorized user!!
Enter your username:
Pisay
Authorized user!!
The adjusted code is below - the only issue is using ” opposed to ".
Also please format you code for future questions.
import java.util.Scanner;
class StringExple{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = "Pisay"; // String input
System.out.println("Enter your username:");
String username = sc.nextLine();
if(username.equals(correctname)){
System.out.println("Authorized user!!");
}else System.out.println("Unauthorized user!!");
if(username.equalsIgnoreCase(correctname)) System.out.println("Authorized user!!");
else System.out.println("Unauthorized user!!");
}
}

Loop through String array to fill it with input from user

just a another noob to Java with a dumb question.
I am trying to create a function that receives a String array and fills it with text input from the user using Bufferedreader (which I currently want to use).
I sort of have the idea in my head but it gives the error cannot find symbol when using the readline() property. How can I achieve this?
public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void fill_array (String parray []){
for(int i = 0; i < parray.length; i++){
parray[i] = in.readline(); //Here it gives me the error
}
}
readLine() and not readline how embarrasing
Hii Scanner is much more simpler than BufferedReader to read input, Let me give you an example :
import java.util.*;
public class Main
{
public static void main(String arp[])
{
Scanner scanner = new Scanner(System.in);
String address = scanner.nextLine(); // read string with spaces
System.out.println("addres : "+ address);
String name = scanner.next(); // read string without spaces
System.out.println("name : "+ name);
Integer age = scanner.nextInt(); // read Integer input
System.out.println("age : "+ age);
}
}
Scanner java api link : https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration

https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();

Console returning first thing Scanner captured without moving onto other blocks of code

I am trying to write a very simple program which captures a few key pieces of info about a prospective job and inserts those into a prepared cover letter. I have imported Java's scanner utility as you can see in my code. When I run it via the "Java" command in windows' cmd prompt, the first System.out.println command appears and I (the user) input as prompted. But then, the console simply outputs exactly what I input and does not move on to other parts of the code. Also, as you can see, the console only outputs the first word of whatever I input.
I am very new at programming, can anyone spot what I must be missing?
I will include an image of the console here (code below):
Link to picture - Lack to reputation needed to edit in photos
find code below
import java.util.Scanner;
public class CoverLetter {
public static void main(String[] args) {
System.out.println("Welcome to tera_byteme's Simple Cover Letter Generator.");
// defines scanner "reader", prompts user to enter business name, stores that in a string var "bizName", closes reader
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the business name.");
String bizName = reader.next();
reader.close();
//same as above block but asks for position title, stores in string var "posTitle"
System.out.println("Please enter position title.");
String posTitle = reader.next();
reader.close();
//"" but asks for user's name, stores in string var "userName"
System.out.println("Please enter your name.");
String userName = reader.next();
reader.close();
String seg1 = new String();
seg1 = "My name is " + userName + " and I am very interested in working for ";
String seg2 = new String();
seg2 = bizName + "as a " + posTitle;
String finalCut = new String();
finalCut = seg1 + seg2;
System.out.println("Here is your cover letter!");
System.out.println(finalCut);
}
}![enter image description here](https://i.stack.imgur.com/EqheW.jpg)
You have two problems you close your scanner too soon and you use next() instead of nextLine(). Don't forget to recompile! I tested those fixes and it works for me. This code:
import java.util.Scanner;
public class CoverLetter {
public static void main(String[] args) {
System.out.println("Welcome to tera_byteme's Simple Cover Letter Generator.");
// defines scanner "reader", prompts user to enter business name, stores that in a string var "bizName", closes reader
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the business name.");
String bizName = reader.nextLine();
//same as above block but asks for position title, stores in string var "posTitle"
System.out.println("Please enter position title.");
String posTitle = reader.nextLine();
//"" but asks for user's name, stores in string var "userName"
System.out.println("Please enter your name.");
String userName = reader.nextLine();
reader.close();
String seg1 = new String();
seg1 = "My name is " + userName + " and I am very interested in working for ";
String seg2 = new String();
seg2 = bizName + " as a " + posTitle;
String finalCut = new String();
finalCut = seg1 + seg2;
System.out.println("Here is your cover letter!");
System.out.println(finalCut);
}
}
Gives this output:
Welcome to tera_byteme's Simple Cover Letter Generator.
Please enter the business name.
Biz Inc.
Please enter position title.
Senior Manager
Please enter your name.
Jeff
Here is your cover letter!
My name is Jeff and I am very interested in working for Biz Inc. as a Senior Manager

JAVA - Newbie trying to get user input

I am an extreme beginner in Java and I can't seem to get the user input. I am using eclipse mars. My code:
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("What is your name?");
Scanner UserName = new Scanner(System.in);
System.out.println(UserName);
}
}
You need to first create your Scanner, then call nextLine on it to get input from the user:
import java.util.Scanner;
class NameAsker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("What is your name? ");
String userName = input.nextLine();
System.out.println("Your name is: " + userName);
}
}
try
System.out.println(UserName.nextLine());
Read Oracle docs for more info
you can use like.
Scanner input=new Scanner(System.in);
if you want to get integer.
int number=input.nextInt();
System.out.Println(number);
for String:
String str=input.nextLine();
There are other method for taking user input like bufferedReader and BufferedInputStream for more details check Java Docs.

Categories

Resources