My code is here:
package test1;
import java.util.*;
public class Test1 {
public static String input;
public Test1(){
Scanner answer = new Scanner(System.in);
String test = answer.next();
}
public static void initializeConstructor(){
Test1 input = new Test1();
}
public static void begin () {
System.out.println("type:");
initializeConstructor();
System.out.println(input);
}
public static void main(String[] args) {
begin();
}
}
I am really new to learning java, my idea is that I can call the constructor to to start the scanner and it will spit back at me what I just typed. I am doing this so I can understand more about constructors in java. However when I run the following program, it just gives me "null". Like I said, i am preety new, so it may be a dumb question but any response would be very appreciated. Thank you in advance.
Because input is null (never assigned), change
String test = answer.next();
to
input = answer.next();
and your code will work. But input is static (it shouldn't be in real code, not if you're setting it in a constructor).
Related
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 2 years ago.
I use Eclipse for programming and it tells me if want to output the "Input String"
Cannot make a static reference to the non-static field Input
Why has the variable to be static in the finally-block?
import java.util.Scanner;
public class NameSort {
String Input;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Inupt some Text");
while (sc.hasNextLine()){
String Input = sc.nextLine();
System.out.println(Input);
if (Input.toLowerCase().equals("ende")) {
System.exit(0);
sc.close();
}
}
} finally {
if (sc != null)
sc.close();
System.out.print(Input);
}
}
}
In Java, you can not use/call a non-static variable/method from a static method. Also, other than the following code, the rest of your code is useless:
import java.util.Scanner;
public class NameSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input;
System.out.println("Inupt some Text");
while (!(input = sc.nextLine()).equals("ende")) {
System.out.println(input);
}
}
}
A sample run:
Inupt some Text
hello
hello
hi
hi
ende
This has nothing to do the finally block, in Java you can't access non-static members or methods from static methods.
You should make Input static if you want to access it from main.
I's trying to build an encoder like the "Enigma Machine" and I have this code so far where I'm trying to get comboOne() to use the "s" variable from main():
import java.io.*;
public class main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What would you like to encode?");
String s = br.readLine();
s.toCharArray();
System.out.println(s);
//comboOne comboOne = new comboOne();
}
}
Just to encode one letter I've written this:
public class comboOne extends main
{
main m = new main();
char message = s.toCharArray();
if(message == 'a')
{
System.out.println('b');
}
}
I am quite new so apologies if I am making an obvious mistake but I think this would be a fun challenge for myself. Please send help and thanks for helping :)
Add outside your Main.main method
public static String s;
Then use Main.s to access the String in a static way. Since it is static it does not need to be instantiated an can directly be called from the class.
I am learning Java and currently attempting to combine if statements and multiple class files.
It is a simple I/O program with a twist, if userName = JDoe I want the program to say something other than the standard saying.
From main.java:
import java.util.Scanner;
import java.lang.String;
class main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
UInput uInput = new UInput();
System.out.println("What is your name: ");
uInput.setName(input.nextLine());
uInput.saying();
}
}
class ifMain {
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
From UInput.java:
public class UInput {
private String userName;
public void setName(String name){
userName = name;
}
public String getName(){
return userName;
}
public void saying(){
System.out.printf("Hello %s", getName());
}
}
However, in class ifMain{}, IntelliJ is saying "Variable userName never used", what am I missing?
See comments:
class ifMain {
public static void main(String[] args){
String userName = "JDoe"; // <=== Declared here
if (test.matches("JDoe")) { // <=== Not used here
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
The local variable userName is never used in the main method of the ifMain class.
You probably meant:
if (test.matches(userName)) {
Side note: The overwhelming convention in Java is that class names start with an uppercase character. So IfMain, not ifMain.
Your program wouldn't even compile in first place. I believe that you are new to Java. But still, look at this code.
class ifMain {//Please change the class name to CamelCase convention
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {// Compile error. Variable test is not declared.
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
Are you trying in a notepad and executing it? You can try using eclipse/NetBeans/IntelliJ IDEs in that case to help you better.
Possible noob question but I cant get my method with parameters in one class to call in the other ?
FirstClass
public class Firstclass {
public static void main(String[] args) {
Test1 test = new Test1();
test.Passingvalue();
test.myMethod();
}
}
SecondClass
import java.util.Scanner;
public class Test1 {
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
String txtFile = Scan.next();
}
public void myMethod(String txtFile){
System.out.print("Scan this file" + txtFile);
}
}
You can provide the parameters as a comma separated list in the brackets after the method's name:
public static void main(String[] args) {
Test1 test = new Test1();
test.myMethod("my_file.txt");
}
Don't forget to add a parameter like this :
test.myMethod("txtFile");
declare your string txtfile as a public static variable outside the two methods (at the beginning of class test1) .
public class Firstclass {
public static void main(String[] args) {
Test1 test = new Test1();
test.Passingvalue();
test.myMethod();
}
}
import java.util.Scanner;
public class Test1 {
String txtFile;
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
txtFile = Scan.next();
}
public void myMethod(){
System.out.print("Scan this file" + txtFile);
}
}
I think you have a misconception here:
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
String txtFile = Scan.next(); //method scope only
}
Here the local variable txtFile only exists until the method Passingvalue (check naming conventions btw) is finished, i.e. it has method scope. Thus when calling myMethod(String txtFile) the parameter has the same name but is a different reference in a different scope.
So you'd either have to pass the file name to your method as the others already suggested or change the scope of txtFile, e.g. make it an instance variable:
public class Test1 {
private String txtFile; //the scope of this variable is the instance, i.e. it exists as long as the instance of Test1 exists.
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
txtFile = Scan.next();
}
public void myMethod(){
System.out.print("Scan this file" + txtFile);
}
}
Please note that this is just meant to illustrate the immediate problem. There are other issues, e.g. with the general design, which are not addressed. The purpose of your code seems to be learning anyways, so design is not that big an issue for now.
Just as a hint: I'd probably pass the name from outside the method or pass/read it in a constructor.
when you are calling a parameterize method you should have to pass a parameter to calling method other wise jvm will not understand to whom method you are calling becuase on the basis of parameters we can over load the methods .
so the final answer of your question is
public static void main(String[] args) {
Test1 test = new Test1();
test.myMethod("place your file name here");
}
I am trying to get user input, however I am getting
illegal start of expression at:
public static String askTheUser() throws IOException
Complete code:
Edit: I have made most of the changes you guys suggested so now I have this:
import java.io.BufferedReader;
public class Driver
{
public static void main(String[]args)
{
Dice dice;
Craps craps;
userResponse = askTheUser();
while(userResponse.equalsIgnoreCase("yes"))
{
craps = new Craps();
while(!craps.gameOver())
{
craps.roll();
//print out results of roll
}
//print out game results: if(craps.gameWon()...
userResponse.askTheUser();
}
}
public static String askTheUser() throws IOException
{
BufferedReader dataIn = new BufferedReader( new InputStreamReader(System.in) );
String data;
System.out.print("Want to play craps? Yes or No");
data = dataIn.readLine();
if(data.equals("y") || data.equals("yes"))
{
return "yes";
}
else
{
return "no";
}
}
}
However I am still getting cannot find symbol at public static String askTheUser() throws IOException. So might I be missing an import that I don't know of?
you declared askTheUser method inside main method. rip it out off the main method.
public static void main(String[]args)
{
//code that goes inside main
}
public static String askTheUser() throws IOException
{
// code that goes in askTheUser
}
and i don't think that keyboard.readline() works?
use:
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
in.readLine(); // Convert to string or int needed!
You can't write method inside method in Java.
But you can have many methods in the same class.
Why? Because of Java specifications.. you are simply not allowed to do so.
Note that you can have an anonymous inner class with methods under another method.