Console input waiting when it should not - java

I've just started working with Java, and I've been trying to get the console input to work properly. Here's the code:
System.out.println("Write a word: ");
Scanner keyboard = new Scanner(System.in);
System.out.println("DEBUG 1");
str = keyboard.nextLine();
System.out.println("DEBUG 2");
System.out.println(str);
This should just take input once and the print the input, like this:
Write a word:
DEBUG 1
Hello //My input
DEBUG 2
Hello //Output
But this is what happens:
Write a word:
Hello //My input
DEBUG 1
//Waiting for new input
DEBUG 2
Hello //The first input
So, it seems to me that it's somehow takes the input at the line Scanner keyboard = new Scanner(System.in); and then put it in my variable str. I use gcj to compile with the following commands to compile and run:
javac hello_world.java
java hello_world
EDIT: I've tried running the program on another computer now, using Ubuntu 10.04 64-bit, instead of Ubuntu 10.04 32-bit as before. I ran it the same way and did not recompile, and the program works fine.
Any ideas why it's behaving like this?

There could be a flushing/buffering issue that causes DEBUG 1 to be output later than you expect. I.e., println("DEBUG 1") could be executed before keyboard.nextLine(), but for some reason the output gets held up on the way, and not output until your input is read.
But I take it that you mean that you actually have to enter two newlines, one after Hello and one at the “Waiting for new input” line. If so, this is more difficult to explain. Perhaps a line termination incompatability issue.
Compiling and executing using the standard JDK gives the behavior you expect.

I checked your program in eclipse running on windows using Oracle JDK 6, I got the expected result.
public static void main(String[] args) {
System.out.println("Write a word: ");
Scanner keyboard = new Scanner(System.in);
System.out.println("DEBUG 1");
String str = keyboard.nextLine();
System.out.println("DEBUG 2");
System.out.println(str);
}
Result :
Write a word:
DEBUG 1
hello
DEBUG 2
hello
OpenJDK is much similar to Oracle JDk and it is available for many distros from their package manager. Can you check with openJDK instead of gcj.

Related

Intellij Idea scanner.nextLine() returns empty String

I've noticed a weird behavior in Intellij Idea Community Edition run window.
Here is my code
Scanner scanner = new Scanner(System.in);
var list = new ArrayList<Integer>();
String[] arr = scanner.nextLine().split(" ");
for (String number : arr) {
list.add(Integer.parseInt(number));
}
// scanner.nextLine();
int n = Integer.parseInt(scanner.nextLine());
When I run it with input
1 2 4 5
3
It will return empty String "" on int n = Integer.parseInt(scanner.nextLine());, unless I uncomment scanner.nextLine() on line 9. Then it works as intended and returns 3.
I have tried to run compiled code in a Terminal window and it works just fine without extra scanner.nextLine().
I am running it on Zorin OS 16.1, IntelliJ IDEA 2022.1.1 (Community Edition) from flathub.
This behavior does not occur when I try it on my Windows 11 machine.
My question is why does it occur and how to have the same behavior on all machines?
As Thomas Kläger pointed out this is a known bug in Intellij Idea 2022.1.1 . Updating to version 2022.1.2 solved the problem.

How to fix "error: class found on application class path: Main" in java for visual studio code

this is my first time posting here and would like how to solve this error message. It appears only sometimes and only lets me build on a program called Main.java. I'm a begginer programmer so please bear with me, this is the code im trying to run:
import java.util.Scanner;
import java.text.NumberFormat;
public class Main {
public static void main(String[] args) {
Scanner priceScanner = new Scanner(System.in);
System.out.print("Price: ");
int price = priceScanner.nextInt();
Scanner interestScanner = new Scanner(System.in);
System.out.print("Interest rate: ");
double interest = interestScanner.nextDouble();
Scanner numberOfPaymentsScanner = new Scanner(System.in);
System.out.print("Number of payments: ");
int numberOfPayments = numberOfPaymentsScanner.nextInt();
Double monthlyInterest = interest / 1200;
Double result = ((double)price * ((interest * Math.pow((1 +
interest), (double)numberOfPayments))/((Math.pow((1 + interest),
(double)numberOfPayments)) - 1)));
NumberFormat currency = NumberFormat.getCurrencyInstance();
String mortgage = currency.format(result);
System.out.println("Your mortgage is: " + mortgage);
}
}
I haven't seen any comprehensible ways to solve this problem online, and the only thing i think could solve it is to reinstall java in another drive and change the classpath.
Thanks for your attention.
I solved it - my mistake. While executing the program using the terminal I was typing java Main.java, whereas the correct execution method was to type java Main.
With Single-file source-code programs which is a new way of executing 1 File Java programs is only available since Java 11. You can run the command:
java (Java File Name without .java extension)
java Main.java
Though please take into consideration that this way of executing only works if your Java project is only 1 Java File.
FYI:
This single-file source code will be executed fully in memory and you can only import code that came with the JDK you are working.
Finally if you want your code to run as fast as possible compile with javac before executing you program.
javac Main.java
java Main
Just be careful that there is no Main.class already in the folder, this may cause a confusion to the compiler.
Step 1:
javac + Filename.java
Step 2:
java + Filename // execute without add .java

Java user console input on sublime text 3 not working

I am trying to get the user to enter their name and have it be printed out on java using Sublime Text 3. After the user enters their name when a message prompts them for it, their name is supposed to be printed out but it justs skips over to a new blank line. It works on online compilers but not on Sublime. How do I get user console input to work on Java Sublime Text 3?
import java.util.Scanner;
public class SocSecProcessor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter name: ");
String name = input.nextLine();
input.close();
System.out.println(name);
}
}
You have to launch execution in a separate console, not the sublime text pseudo console.
The solution is to launch with START command in a batch file .bat
for example:
START CMD /K %RELATIVE_PATH%\jdk\bin\java -cp %~dp1 %~n1
where %1 is the file class with main method. Go to the batch syntax documentation if necessary... Your build system in sublime must launch a batch file with this kind of
instruction.

How to make input ( Scanner ) work on Sublime Text 3 when using JAVA?

I just started learning JAVA and Sublime Text 3 was proposed to me as a great compiler for JAVA code. I downloaded it, started programming and set my build system as JavaC. I wanted to create a quick program adding two numbers given by the user and displaying the result but nothing comes up in the "build" section. Do you have any idea to make that work ?
Here is the code I wanna try:
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
int a,b;
Scanner input=new Scanner(System.in);
System.out.println("Enter a number:");
a=input.nextInt();
System.out.println("Enter a number:");
b=input.nextInt();
System.out.println("sum=" + (a+b));
}
}
For future references on how this windows command line or command prompt in windows works.
First check if your computer have the JRE (required to run a Java program) and JDK ( required compile and run Java programs) already install to verify this input the text "java -version" and javac -version into the Command Line. If the Javac is already intalls, however, doesn't show in the command line then you need to follow this sites on how to set up the path depending on your OS.

Cannot find the scanner

I have a very bad experienced about the scanner because I am using GUI and JOptionPane. So I am not be able to do the program's interns of scanner because. I am new to it so Please help me, "cannot find the scanner". This is my code so far .
import java.io.*;
import java.util.*;
class MultiplicationTables{
public static void main(String args[]){
int n, c;
System.out.println("Enter an integer to print its multiplication table");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication table of "+n+" is :-");
for ( c = 1 ; c <= 10 ; c++ )
System.out.println(n+"*"+c+" = "+(n*c));
}
}
If your Java is not version 1.5 or above, Scanner class is not provided.
go to command promt
type "java -version"
check your version.If you have outdated just update. Problem shoud be fixed..
and make sure your IDE or the JDK actually use it.
Code that you have here provided is correct so you can use it after you fix your problem.
First import is redundant.
import java.io.*; // you can remove it
Scanner is a class in java.util package.
Check weather you have properly set your jdk path in your ide, or in your system.
Depends on system that you use:
Windows: Advanced System Settings->Environment Variables->Path check weather there is your path to jdk.
UNIX in console print 'echo $PATCH' and check that if you have there jdk path properly added.
And then you can check your version of java independent to system in console writing
java --version

Categories