Missing identifier even though it's defined one line above? - java

Let's see this trivial Java program:
class A {
public static void main(String[] args) {
int а = 2;
System.out.println("a " + a);
}
}
It creates the variable a initialized to 2, and prints it. However, it doesn't compile:
$ javac A.java && java A
A.java:4: cannot find symbol
symbol : variable a
location: class A
System.out.println("a " + a);
^
1 error
Why?

You've got two different types of a there. If you retype the first one as ASCII a, it's fine.
The first a is U+0430, "Cyrrilic small letter a". (See the relevant Unicode chart.)
I would personally try to keep all identifiers in Java as ASCII characters where possible.
(Where did this code even come from to start with?)

I don't know what is that, but on the int а = 2; line, that thing most certainly is not an a, a.k.a ASCII 97.

Related

What happens if the first letter of a method in a java program is a capital / upper case letter?

I am aware that in Java language, the first letter of a method should desirably be lower case, but what happens if it becomes a capital letter?
I tried changing the first letter of the methods in my program to capital letters, but it made no difference.
import java.util.Scanner;
class Replace3meth
{
String str, newstr;
int len, vcount;
public void Accept()
{ // obtaining input
System.out.println("\f");//clearing the screen
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
str = sc.nextLine();
str = str.toLowerCase();
} // accept() method ends
public void ReplaceVowel()
{
len = str.length();
newstr = "";
vcount = 0;
char c;
for (int i = 0; i < len; i++)
{ // finding no. of vowels
c = str.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
c = Character.toUpperCase(c);
vcount++;
} // if function ends
newstr = newstr + c;
} // for loop ends
} // replaceVowel() method ends
public void Display()
{ // printing output
System.out.println("Original sentence:" +str);
System.out.println("New sentence: "+newstr);
System.out.println("No. of vowels: "+vcount);
} // display() method ends
public static void Main()
{ // calling all methods
Replace3meth obj = new Replace3meth();
obj.Accept();
obj.ReplaceVowel();
obj.Display();
} // main() method ends
} // class ends
This is a simple program to convert all the vowels in a sentence to upper case. Even after changing all the method names to start with a capital letter, the program worked properly.
PS: I use BlueJ (not VSCode), so I can used main() instead of main(String[] args)
Method names don't have to start with a lower case letter. It's just a shared convention so all developers are on the same page and people reading your code don't have to add extra cognitive load to quickly parse it.
Method names are case-sensitive, though. So if, for any reason, a name is expected to have a certain case it has to be respected.
One example is methods that need to be implemented because they are declared in an interface or abstract class (if the method you have to implement is called doStuff you can't implement it as DoStuff or dostuff).
Another example is the main method, which is the method the JVM expects to call when you run a class. It has to maintain the same case (and the fact that it has to be public, static, void and have an array of strings as its only argument), so you can't call it Main or MaiN. But that is a requirement of the JVM, not of the language.
Nothing happens, the code will still compile. You can name your methods getName, GETname, getNAME, GETNAME, or GeTnAmE and the compiler will not care.
Who will care however are human people reading and trying to understand the code. Make it easy for your fellow programmers and future you to read code.
You could also name them föΘBÄRẞ and your code will still compile. But nobody reading the code could make any sense of it.
Usually nothing special happens to the code itself, but other people used to the conventional style will have troubles understanding it and therefore you will e.g. have a lower rate of answers to your SO-questions if they contain code that doesn't follow the conventions.
But because you mentioned it extra:
To start a java program with the java command (this is the standard way), your main method has to have a defined signature, as stated in the documentation The java Command:
The method declaration has the following form:
public static void main(String[] args)
So in this case, if your main method is named Main and doesn't have that exact give signature (public static, no return value, array of String as parameter), your program will not start.
And of course if you are overloading or overwriting or implementing methods from other classes or interfaces, you have to copy their name exactly and must not change the case - and as e.g. overwriting of equals and hashcode from the Object class are quit common, it would result in a mixture of casing, and from my experience I can say this is super confusing - even if you want to understand your own code a few days after you wrote it.
Syntax wise it wont make any difference but the standard says that you should be following camel case when naming methods or variables.
An Excerpt from official doc.
"Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized."
https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html

How to allow Java to take in /n from scanner and print ASCII value

I'm doing a java project on codeZinger where I need to take in a character value from the scanner and print the ASCII value. So far the code I have works for everything besides the "/n" character. In that case, codezinger returns the error "Exception in thread "main" java.lang.NullPointerException scanner".
I have attached my code below, I've tried everything and it won't work. I'm new to java from c++.
I tried even manually testing for /n using an if statement and that didn't work
public class Solution {
public static void main(String[] args) {
//creating input stream
Scanner input = new Scanner(System.in);
// allows character input from input stream
char charIn = input.findInLine(".").charAt(0);
if(input.equals("\\n"))
{
System.out.print("10");
}
// casts character to type int to get ascii value
int intVal = (int)charIn;
System.out.print(intVal);
}
}
input.equals() method in java never takes its parameter in apostrophe.
Please go through this once :
https://www.jquery-az.com/learn-java-equals-method-5-examples/
Moreover /n doesn't exist in java. If you have to print a line(Give a break) then you have to use System.out.println() , simply, and it will be printed in next line.
Also go through this for printing ASCII value
https://www.javatpoint.com/how-to-print-ascii-value-in-java
int code;
while ((code = System.in.read()) != -1) {
System.out.format("0x%02X ", code);
}

Keep on getting a "Cannot find symbol" on my simple Java program and don't know why

So, here's my code:
import java.util.Scanner;
public class FootballsGivenAway
{
public static void main(String [] args)
{
int FinalScore;
**int TouchdownNumber=BallsGivenAway;**
int BallsGivenAway=TouchdownNumber;
Scanner inputDevice= new Scanner(System.in);
System.out.print("What was the final score of the Carolina Panthers? ");
FinalScore=inputDevice.nextInt();
System.out.print("Out of the points the Panthers scored, how many of them were touchdowns? ");
TouchdownNumber=inputDevice.nextInt();
System.out.println("The Carolina Panthers gave away this number of footballs today: " + BallsGivenAway);
}
}
The compiler keeps returning the "Cannot find symbol" error on the line in bold. What must I do to correct this issue?
You can't use a local variable in Java before you've declared it. If you look at your code, you can see that you're trying to set TouchdownNumber to BallsGivenAway before you've declared BallsGivenAway on the next line.
Also:
You're trying to set BallsGivenAway back to TouchDownNumber? You're defining two variables whose value is supposed to be ... the other one?
Idiomatic Java uses camelCase variable names like finalScore, ballsGivenAway. It's just a style issue, but you might as well get used to it now.

First Ever Java Program Incorrect Output

Sorry for really stupid question, I'm learning a new language and taking this code:
public class Exercise01 {
int i;
char c;
public static void main(String[] args) {
Exercise01 E = new Exercise01();
System.out.println("i = " + E.i);
System.out.println("c = [" + E.c + "]");
}
}
/* Output:
i = 0
c = [
*/
Why the output does not produce "]" character? Has it something to do with Unicode?
PostEdited: the variable E.c was not initialized for experimentation purpose.
It may be that the place your program is outputting to, a console or a window, is getting confused by the U+0000 character which is the value of E.c.
It works fine for me.
Initialize E.c and try again.
You are trying to print the null character as your char c hasn't need initialised. i.e. \0 Interestingly you can't copy and paste this character easily as most C code sees this as an end of string marker.
I see the ] when I run the code.
Try changing your code with
char c = '?';
gives me an output of
i = 0
c = [?]
One way to reproduce this problem is to run on unix
java Main | more
which outputs
i = 0
c = [
Probably has to do with the fact that E.c isn't initialized to anything
I think it is because c is not initialized and therefore holds \0, i.e. "end of line". So, println prints until end of line and does not print your ]
You should initialize your char C as well as the int i. Good code practice: It is important to initialize your variable once you declare a variable!

Programs that reproduces itself

Is it possible to make a Java program that prints its source code to a new file, and compiles it, and runs the compiled program?
Update:
Okay, might as well make it autorun. Enjoy the madness. Run at your own risk.
Yes it's possible, because I actually wrote it up. It doesn't do the RUN part (that's just too crazy, because as others have mentioned, it will cause an infinite loop), but here it is: Quine.java
import java.io.*;
public class Quine {
public static void main(String[] args) throws Exception {
char q = 34;
String out = "Quine$";
String text = (
"import java.io.*; " +
"public class [OUT] { " +
"public static void main(String[] args) throws Exception { " +
"char q = 34; String out = `[OUT]$`; String text = `[TEXT]`; " +
"PrintWriter pw = new PrintWriter(out + `.java`); " +
"pw.format(text, 34, out, text); " +
"pw.close(); Runtime runtime = Runtime.getRuntime(); " +
"runtime.exec(`javac ` + out + `.java`).waitFor(); " +
"runtime.exec(`java ` + out); " +
"} " +
"}"
).replace("`", "%1$c").replace("[OUT]", "%2$s").replace("[TEXT]", "%3$s");
PrintWriter pw = new PrintWriter(out + ".java");
pw.format(text, 34, out, text);
pw.close();
Runtime runtime = Runtime.getRuntime();
runtime.exec("javac " + out + ".java").waitFor();
runtime.exec("java " + out);
}
}
So here's how to get the craziness to start:
javac Quine.java to compile
java Quine to run it
It will produce, compile and run Quine$
I've made sure Quine.java is as readable as possible, so the major difference from Quine$.java are formatting and the 3x replace. The minor difference is that Quine$.java has out set to Quine$$.
Quine$ will produce, compile and run Quine$$
Quine$$ will produce, compile and run Quine$$$
Quine$$$ will produce, compile and run Quine$$$$
...
Do note that this doesn't do any reverse-engineering or cheat by reading the .java source code, etc. Quine is a quine-generator because it produces a different code differently formatted, but Quine$ is pretty much a true self-contained quine: it does reproduce itself, it just relabels it Quine$$ (which reproduces itself and relabels to Quine$$$ etc).
So technically there's no infinite loop: it will eventually come to a halt when the file system can't handle another $. I was able to manually stop the madness by forcefully deleting all Quine$* files, but run at your own risk!!!
Yes, it is possible.
A trivial implementation would be: have the source code contain itself in a string, save the string to a file and fill its own string with the same string (otherwise, the initial string would be of infinite size, due to the recursive manner of this implementation), compile the file, and run the compiled file (which will, in turn, do the very same).
Non-trivial implementations are significantly harder.
Sure it works - Have a look at rosetta code and navigate to Quine, which is a self-referential program that can, without any external access, output its own source.
There's one example for a quine in Java.
Programs that reproduces itself or Self Replicating Programs are known as Quine Programs
Sample Program in Java which reproduces itself.
public class QuineProgram {
public static void main(String[] args){
String f = "public class QuineProgram { "
+ "public static void main(String[] args)"
+ "{ String f =%c%s%1$c;"
+ " System.out.printf(f,34,f);}} ";
System.out.printf(f, 34, f);
}
}
Output:
public class QuineProgram { public static void main(String[] args){ String f ="public class QuineProgram { public static void main(String[] args){ String f =%c%s%1$c; System.out.printf(f,34,f);}} "; System.out.printf(f,34,f);}}
You could use the Java Compiler API (JSR-199) for this. Below, code from the JSR-199 that compiles code from a String (slightly modified to make it compile). The code actually compiles source code from the String into a byte array (i.e. it doesn't write to disk), loads it and then executes it via reflection:
MemoryFileManager.java: A file manager for compiling strings to byte arrays.
ByteArrayClassLoader.java: A class loader which loads classes from byte arrays.
CompileFromString.java: The class that wrap everything together.
That could be a starting point (credits to Peter Van der Ahé, the original author).
BTW, you need of course a JDK to use this API.
I don't know exactly what you want, but I think BeanShell is something you can use.
BeanShell is an interpreter. You can run uncompiled Java-code (So you give it a String with code and he runs it).
Of course if you really want to do what you wrote, the machine where the program is running needs a JDK to compile your program.
Hope this helps
I dont think it will work in Java. Wouldn't that involve overwriting a running class file.
Suppose your program is in Quine.java compiled to Quine.class.
Now Quine.class will attempt to write its output to Quine.java (so far so good), and compile it to Quine.class. This is gonna be a problem as Quine.class is already running
Yes - don't forget to use a JDK instead of a JRE:
Bundle the app's source code files with the app. The app would copy the source files to a new set of source code files, compile the new source files, bundle the new source code with the new class files into a new app, and then spawn the new app.
or
Bundle a decompiler with the app. The app would run the decompiler on its own class files to generate new source code files, compile the new source files, bundle the decompiler with the new class files into a new app, and then spawn the new app.
Here's a Java Quine using preview text block feature (-source 13 --enable-preview) where output is formatted the same as input:
package org.sample.quine;
public class QuineProgram
{
public static void main(String...args)
{
String f ="""
package org.sample.quine;
public class QuineProgram
{
public static void main(String...args)
{
String f =""%c%c%s%1$c"";
System.out.printf(f, 34, 10, f);
}
}
""";
System.out.printf(f, 34, 10, f);
}
}
Output:
package org.sample.quine;
public class QuineProgram
{
public static void main(String...args)
{
String f ="""
package org.sample.quine;
public class QuineProgram
{
public static void main(String...args)
{
String f =""%c%c%s%1$c"";
System.out.printf(f, 34, 10, f);
}
}
""";
System.out.printf(f, 34, 10, f);
}
}
Heavily Commented Version:
package org.sample.quine;
public class Quine
{
public static void main(String...args)
{
// Inside text block use "" followed by token or token followed by "" so that we don't prematurely close text block
String f ="""
package org.sample.quine;
public class Quine
{
public static void main(String...args)
{
// Inside text block use "" followed by token or token followed by "" so that we don't prematurely close text block
String f =""%c%c%s%1$c"";
/* Tokens in template text block, each prefixed with percent symbol
* 1(c) third quote (34) of open block delimiter
* 2(c) new line (10) of open block delimiter
* 3(s) String f text block that goes between two text block delimiters
* 4(1$c) first quote (34) of close block delimiter,
* 1$ means first argument after template argument
* 2$ would be second argument after template argument
*/
// Arguments - 1 template (String f); 2 "; 3 newline; 4 template again without replacing tokens
System.out.printf(f, 34, 10, f);
}
}
""";
/* Tokens in template text block, each prefixed with percent symbol
* 1(c) third quote (34) of open block delimiter
* 2(c) new line (10) of open block delimiter
* 3(s) String f text block that goes between two text block delimiters
* 4(1$c) first quote (34) of close block delimiter,
* 1$ means first argument after template argument
* 2$ would be second argument after template argument
*/
// Arguments - 1 template (String f); 2 "; 3 newline; 4 template again without replacing tokens
System.out.printf(f, 34, 10, f);
}
}

Categories

Resources