New to java; how do I make the String static within conditionals? - java

public class testing {
public static void main(String[] args)
{
boolean a = true;
if (a) {
public static String word = " ";
}
else if (a == false) {
public static String word = "not";
}
System.out.println(word);
}
}
Instead of printing the value, it tells me "Illegal modifier for the variable word; only final is permitted.
I tried to use public static final String word = "not";
but I still got an error saying that it is wrong.

The variable should be created outside of your main:
public class Testing {
public static String word;
public static void main(String[] args)
{
boolean a = true;
if (a) {
word = " ";
} else {
word = "not";
}
System.out.println(word);
}
}
Alternatively you can create a variable inside you main as well.
public class Testing {
public static void main(String[] args)
{
boolean a = true;
String word;
if (a) {
word = " ";
} else {
word = "not";
}
System.out.println(word);
}
}

When variables, blocks or methods are made static, they are made available during load time. Rest all reserves memory during run time. All the local variables created inside a static method are present in the method stack, which as a package is already present during load time. So creating a static variable inside method, be it be static or non-static method, is not allowed.

Related

Java returning null and result

can someone take a look at this example and tell me why I get null10 as printed value instead of 10 only?
and is there and easier solution for this program without using global String variable "word"
public class UserInput {
public static String word;
public static class TextInput {
public void add(char c) {
word = word + c;
}
public static String getValue() {
return word;
}
}
public static class NumericInput extends TextInput {
#Override
public void add(char c) {
if (Character.isDigit(c)){
word = word + c;
}
}
}
public static void main(String[] args) {
TextInput input = new NumericInput();
input.add('1');
input.add('a');
input.add('0');
System.out.println(input.getValue());
}
}
EDIT: I need use inherits from TextInput
You need to give your static word field an initial value, otherwise it will default to being null. And when Java concatenates String objects, it will treat a null reference as the literal string "null". So you're effectively always starting off with the String "null".
If you give your class field a starting value of "" (empty string) then your code should do what you expect.
With regard to a better way of doing this, I would instead give the class a non-static field of type StringBuilder (and initialise it so that it's not null). Then your add method can simply append(c) the new characters to the StringBuilder field object, which will be more efficient than repeatedly using string concatenation (which is what you get with word + c).
You are not initializing input, so it is null. You need to initialize input first in order to make concatenating work.
So, use this:
public static String word = "";
Rather than using a static variable that is shared over all instances and children of the TextInput class, you should be using an instance variable.
You'll still have to initialize a non null value
That would look like
public static class TextInput {
protected String word;
public TextInput() {
this.word = "";
}
public void add(char c) {
word = word + c;
}
public String getValue() {
return word;
}
}
To better understand the problem, try your code with this
TextInput input = new TextInput();
input.add('a');
System.out.println(input.getValue());
TextInput input2 = new NumericInput();
input2.add('1');
input2.add('0');
System.out.println(input2.getValue());
Additional, see #Bobulous comment about using StringBuilder
You were not initializing the "word".
public class TextInput {
public static String word=""; // a lil change here
public static class TextInput {
public void add(char c) {
word += c;
}
public String getValue() {
return word;
}
}
public static class NumericInput extends TextInput {
public void add(char c) {
if (Character.isDigit(c)){
word += c;
}
}
}
public static void main(String[] args) {
NumericInput input = new NumericInput();
input.add('1');
input.add('a');
input.add('0');
System.out.print(input.getValue());
}
}

Dynamic string concat in java

I want to contact two string.
Here my code
public class StringTest {
public String concat = "";
public String txt = "Hello "+concat;
protected void print() {
System.out.println("Output: " + txt);
}
public static void main(String[] args) {
StringTest tb = new StringTest();
tb.concat = "World";
tb.print();
}
}
Output: Hello
But I need "Hello World".
It's possible ?
Conditions:
Should't re-assign variable (get/set , inside method)
For the execution to be dynamic you need a method.
public class StringTest {
public String concat = "";
private String txt() { return "Hello "+concat; }
protected void print() {
System.out.println("Output: " + txt());
}
public static void main(String[] args) {
StringTest tb = new StringTest();
tb.concat = "World";
tb.print();
}
}
A field is only calculated when you write an assignment = but a method is evaluated each time it is called.
You can't change the constant String once declared in that way, and that too it is private, you can't access that variable outside.
You almost there but you have to change your Structure and concatination won't work that way.
public class StringTest {
private String txt = "Hello ";
protected void print() {
System.out.println("Output: " + txt);
}
protected void concat(String toBe) {
txt = txt + toBe;
}
public static void main(String[] args) {
StringTest tb = new StringTest();
tb.concat("World");
tb.print();
}
}
The value in concat only will be assigned to txt variable when you create a StringText. Instantiate the correct from to concatenate value dynamically and assign this value inside print method like this
public String concat = "";
private String txt = "Hello ";
protected void print() {
txt = txt.concat(concat);
System.out.println("Output: " + txt);
}
public static void main(String[] args) {
StringTest tb = new StringTest();
tb.concat = "World";
tb.print();
}
each call to print method add value contained in concat variable.

Java scrabble game unexpected error

On the line where I commented "ERROR HERE" I am getting an error stating "non static variable this cannot be referenced from a non-static context". But when I remove static from my methods, it runs and I get "Error: Main method is not static in class scrabble.Scrabble, please define the main method as:
public static void main(String[] args)". Not sure what is causing this.
package scrabble;
public class Scrabble {
class Tile{
int value;
char letter;
public Tile (char letter, int value) {
this.letter=letter;
this.value=value;
}
}
private static void printTile(Tile letter) {
System.out.print("Letter is: " + letter.letter);
System.out.println(" and the value is " + letter.value);
}
public static void testTile() {
Tile L1 = new Tile('z', 10); //ERROR HERE
printTile(L1);
}
public static void main(String[] args) {
testTile();
}
}
put the Title class in a separated file Title.java in the same package
package scrable
and make it public. that will work for you. :)

How to run method from other class

Here's my code:
public class Oddmain {
public static void main(String[] args) {
}
private static void comp() {
for (int i = 1; i <= 10; i += 2) {
System.out.print(i + " ");
}
}
}
I want it to print out only odd numbers between 1 and 10, which it does fine. The thing I'm curious about is making it in another class, and calling upon it in the main method. How would I have the main method call upon something from another class?
I tried using the run method:
public void run();
//my for loop here
But that didn't really work. Whenever I move:
private static void comp() {
for (int i = 1; i <= 10; i += 2) {
System.out.print(i + " ");
}
}
to the other class, it says this:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method comp() is undefined for the type Oddmain
at Oddmain.main(Oddmain.java:4)
I think that this means it want me to create the method comp() in this class (Oddmain), but I want to create in the class Oddcomp. This is something I can do, correct?
I'm really new to coding, so please explain stuff very thorough when posting, so I know why I'm doing what I'm doing, and not just copy/pasting.
The problem that you have here it's that you don't close main method.
public class Oddmain {
public static void main(String[] args){
}
private static void comp() {
for(int i = 1; i <= 10; i += 2){
System.out.print(i + " ");
}
}
}
And now you can call your method comp from your main method:
public static void main(String[] args){
comp();
}
I expect it will be helpful for you!
public class Oddmain {
public static void main(String[] args){
private static void comp() {
for(int i = 1; i <= 10; i += 2){
System.out.print(i + " ");
}
}
}
There is no way this code works fine, you cannot create a new method with in the main statement. I believe you meant:
public class Oddmain {
public static void main(String[] args){
comp();
}
private static void comp() {
for(int i = 1; i <= 10; i += 2){
System.out.print(i + " ");
}
}
}
To utilise the comp method in another class you can go about this in two ways...
NOTE: In both cases you must change the access modifier of your method from private if you wish to use the method in another class.
Private fields can only be accessed with in the class they are defined in.
1) Create an instance of Oddmain in your other class.
public class OtherClass {
public static void main(String[] args){
Oddmain s1 = new Oddmain();
Oddmain.comp();
}
}
2) Call the comp() method in a static manner, static methods are often called by using the class name the static method is defined in, e.g.
Oddmain.comp();
Static methods should often be called via the latter format. In both cases you are calling the comp method in Oddmain. Remember static fields belong to a class not an object.

I'm getting errors about expected indentifiers and I'm not sure why

Actually the following program is a module of my actual program and I get expected identifier errors in this code.
class New
{
static void check(String m)
{
int start=0,end=0;
char ch[]=m.toCharArray();
for(int i=0;i<m.length();i++)
{
start=end;
if(ch[i]==32)
{
end=i;
break;
}
count(ch,start,end);
}
}
static void count(char chq[],int initial,int final)
{
//String s=new String(chq,initial,final);
System.out.println(initial+" is Initial");
System.out.println(final+" is final");
}
public static void main(String... s)
{
String k="India is a Good Nation. I Love my India";
check(k);
}
}
Probably because of you are using final as a parameter name in count method. final is a keyword in java which can not be used as a parameter name or variable name. Try -
static void count(char chq[],int initial, final int end)
{
//String s=new String(chq,initial,final);
System.out.println(initial+" is Initial");
System.out.println(end+" is final");
}
instead of
static void count(char chq[],int initial,int final)
{
//String s=new String(chq,initial,final);
System.out.println(initial+" is Initial");
System.out.println(final+" is final");
}

Categories