I've wrote a programme to mask the input that a user types in at the command line.
In detail:
When my programme starts, I run a new thread that prints out an asterisk every millisecond via System.out.print("\010*").
Meanwhile my main method reads in the users input via read.nextLine().
When I run this programme in eclipse, the output is an overflow of asterisks (which is what I would expect).
However, when I run this programme from my terminal, I only see an asterisk appear whenever I type a character.
Why is this? I read some other articles saying how the CPU only allocates 6-10% of memory to the command line, whereas a typical IDE gets more than twice this.
My code is shown below just for reference:
import java.util.Scanner;
public class Main {
public static void main(String [] args){
PasswordMasker passwordMasker = new PasswordMasker();
passwordMasker.start();
Scanner scan = new Scanner(System.in);
String password = scan.nextLine();
passwordMasker.stopMasking();
System.out.println("The password is: " + password);
}
}
public class PasswordMasker extends Thread {
private boolean maskInProgress = true;
public void run(){
mask();
}
private void mask() {
while(maskInProgress){
try {
Thread.sleep(1);
System.out.print("\010*");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Masking stopped");
}
public void stopMasking(){
this.maskInProgress = false;
}
}
Because the Eclipse console can't display backspace character (\b or \010),
because of bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=76936
The cmd can display it, that is why your program works as expected in cmd.
However the fix will be available in Eclipse 4.5 M4, according to the bug report.
Related
The code is supposed to read an unidentified number of inputs from the keyboard and return any tabs as *. My program seems to work when I run it in eclipse and get no errors. When I turn in the code on the submission website, this is the error I get.
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1589) at replaceHW.main(replaceHW.java:9)
import java.util.Scanner;
public class replaceHW {
public static void main(String[] args) {
//write a program that converts all TABS in your code
//with STARS i.e. *
Scanner in = new Scanner(System.in);
String ans;
while(!(ans = in.nextLine()).equals(""))
System.out.println(ans.replace("\t","*"));
}
}
Your problem is simple: nextLine() works in tandem with hasNextLine(): the correct code is:
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextLine()) {
String line = in.nextLine();
if (!"".equals(line)) {
System.out.println(ans.replace("\t","*"));
}
}
The try-with-resources is best practice. But be wary than with System.in, it will close it when done.
hasNextLine() will try to read has much input is needed to find a line.
I have written the code to print the minimum number of insertions required to make any string a palindrome . The code runs perfectly when written on notepad and compiled through cmd. But it gives Exception when run at any online java compiler.
Here is the code:
import java.io.*;
import java.util.Scanner;
class Solution
{
public void disp(String s)
{
int l=s.length();
int pos=-1;
for(int i=l-1;i>0;i--)
{
char b=s.charAt(i);
char b1=s.charAt(i-1);
if(b!=b1)
{
pos=i;
break;
}
}
String w=s.substring(0,pos);
int l1=w.length();
int count=0;
for(int i=0;i<l1;i++)
{
char b=w.charAt(i);
count++;
}
System.out.println(count);
}
}
public class scanner_call
{
public static void main(String[] args)throws InterruptedException
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the one line string");
String s=sc.next();
Solution p1=new Solution();
p1.disp(s);
}
}
The online compiler shows this exception.
Enter the one line string
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at scanner_call.main(scanner_call.java:39)
Why this very program runs perfectly in notepad but raises Exception in online compilers? What should i do?
This is because your program requires input detection, but the online compiler you use might not have input capability.
Try this: https://www.tutorialspoint.com/compile_java_online.php
Put your Source Code into the Source Code tab
Put your input into the STDIN (fyi, I put "asd" in there and worked fine)
Then you should see some result, to change the input, change the STDIN
I can't get my .jar files to run. I have read many similar threads but still can't get it working. I can get it to run from the cmd line if I run "java -jar jar_name.jar" from the folder that contains the file. I ran the Jarfix program that is supposed to fix the file association, but it still does not work. When I export from Eclipse it tells me
JAR export finished with warnings. See details for additional information....Exported with compile warnings: Shutdown/src/Shutdown.java
From what I've read, this is not a real issue, it just means there are warnings in your program. I don't think there's any problem with the code, but it's a small program so I've included it anyways. Any help is appreciated.
import java.io.IOException;
import java.util.Scanner;
public class Shutdown {
public static void main(String[] args) throws IOException
{
String os;
String Win = "Windows";
String choice;
os = System.getProperty("os.name");
if(os.contains(Win))
{
System.out.println("Congratulations, you are running "+ os + ".\nYou now have three options.");
do
{
PrintMenu();
Scanner keyboard = new Scanner(System.in);
choice = keyboard.next();
ReturnMenu(choice);//passes user input as argument to method
}
while(choice !="1" || choice != "2" || choice !="3");
}
else
System.out.println("You Are Using A Non-Windows System. Please upgrade.");
}
public static void shutdown() throws IOException
{
Runtime run = Runtime.getRuntime();
Process proc = run.exec("shutdown -s -t 0");
}
public static void restart() throws IOException
{
Runtime run = Runtime.getRuntime();
Process proc = run.exec("shutdown -r -t 0");
}
public static void logoff() throws IOException
{
Runtime run = Runtime.getRuntime();
Process proc = run.exec("shutdown -l");
}
public static void PrintMenu()
{
System.out.println("Please make a selection:"
+ "\n1 - Shut down\n2 - Restart\n3 - Log Off\n");
}
public static void ReturnMenu(String in) throws IOException, NumberFormatException
{
int x;
try
{
x = Integer.parseInt(in);//cast user input to int to be used in switch statement
}
catch (NumberFormatException e)//catches non-number input that can't be case to int
{
x=4;//caught exception sets x to 4 to cause loop to keep running
}
switch (x)
{
case 1:
shutdown();
break;
case 2:
restart();
break;
case 3:
logoff();
break;
default:
System.out.println("Invalid menu selection. Please try again.");
}
}
}
Select your File/Project -- Export -- Runnable JAR -- Select class with main() in
Launch Configuration -- destination
If you want dependencies for your class in the generated JAR, select
1st option (Extract required libraries into generated JAR)
If you don't need them but just your code, select 3rd option (Copy
required libraries into a sub-folder next to generated JAR)
Hope this helps :)
On Windows, a standard Java installation associates double-clicking of .jar files with the javaw.exe program, not java.exe. The difference is that javaw.exe has no console (command window).
Since you have no console, you have no System.in. I haven't had a chance to try it, but my guess is that attempting to read from System.in will result in immediately reaching the end of the stream, which will cause a Scanner's next* methods to throw a NoSuchElementException.
Im summary, you can't use System.in. If you want to prompt the user for input, use Swing or JavaFX.
Additional note: You must not compare Strings using == or != in Java, as those operators compare object references instead of comparing String values. Use the equals method instead. For instance:
while (!choice.equals("1") && !choice.equals("2") && !choice.equals("3"))
I have problems with reading user input from java lanterna library terminal. Upon key strike I would like the system to print a certain character on the terminal. I use this code:
public class Snake {
public static void main(String[] args) {
Terminal terminal = TerminalFacade.createTerminal(System.in, System.out, Charset.forName("UTF8"));
terminal.enterPrivateMode();
Key key =terminal.readInput();
if (key.getKind() == Key.Kind.Tab)
{
terminal.moveCursor(100, 100);
terminal.putCharacter('D');
}
}
}
Unfortunately, I only have terminal opened - I cannot do any input. Anybody has an idea why this happens?
Based on the given code, it seems that you are only running through your if statement once before the main method is finished executing.
Try implementing a while loop to continuously search for input like so:
public static void main(String[] args) {
Terminal terminal = TerminalFacade.createTerminal(System.in, System.out, Charset.forName("UTF8"));
terminal.enterPrivateMode();
// I would recommend changing "true" to a boolean variable that you can flip with a key press.
// For example, the "esc" key to exit the while loop and close the program
Key key;
while(true){
// Read input
key = terminal.readInput();
// Check the input for the "tab" key
if (key.getKind() == Key.Kind.Tab){
terminal.moveCursor(100, 100);
terminal.putCharacter('D');
}
}
terminal.exitPrivateMode();
}
Additionally, check out the Lanterna development guide.
When I am running a simple java program in eclipse, when I run it, the console flashes what it should, then it disappears.
public class apples {
public static void main(String[] args) {
int age = 60;
if (age < 50) {
System.out.println("You are young");
} else {
System.out.println("You are old");
}
}
}
Your program is immediately terminating after printing what needed to be printed. You can use several methods to keep the console on the screen.
Your program is immediately terminating after printing what needed to be printed. You can use several methods to keep the console on the screen. One possibility is to use
while(true);
to stop the application from exiting. Beware that you should only use this for debugging methods!
Another, probably better, way is to ask for input before closing the window.
Simply read a line from standard input. Your program will wait until you type something and only then exit.
Scanner sc = new Scanner(System.in); // create a scanner that will read from standard input
String s = sc.nextLine(); // You don't even need to save the return value of
// sc.nextLine() here