Java scanner not working - java

This CSV reader which also checks the validity of an email address and password through the use of the map tool.
import java.io.*;
import java.util.*;
public class CSVReaders{
public static void run(String[] args) throws Exception {
Map<String, String> emailPasswordMap = new HashMap<String, String> ();
BufferedReader CSVFile =
new BufferedReader(new FileReader("testa453.csv"));
String dataRow = CSVFile.readLine();
while (dataRow != null){
String[] dataArray = dataRow.split(",");
emailPasswordMap.put (dataArray[0], dataArray[1]);
dataRow = CSVFile.readLine();
}
CSVFile.close();
//Scanner in = new Scanner(System.in);
//String email = in.nextLine();
//String password = in.nextLine();
String password = ("raj45");
String email = ("rakhter#bluebell.org");
if (password.equals (emailPasswordMap.get (email))) {
System.out.println ("The entered email and password are valid");
}
else {
System.out.println ("The entered email and password are invalid");
}
}
}
The problem which I am getting is that upon runing when i change the '//' over to the string password and email and attempt to use the scanner which I have included the program 'runs' but console window does not appear and I have to force stop the program to stop it running. Whilst using it as I have shown here it works perfectly. Previously I had an error with the scanner that related to static and non-static variables. I have looked them up and attempted to use instance variables but to little success.
Is the way in which I have declared the scanner wrong or can I not use Mapping in conjuction with the scanner?
EDIT: I am currently using BlueJ on Mac since I am reasonably new to java programming. And yes it does work as I have quoted it, it only stops working when I try to use the scanner.

Is the way in which I have declared the scanner wrong or can I not use Mapping in conjuction with the scanner?
The Scanner declaration appears to be correct. No, there is no restriction prohibiting the simultaneous use of any two parts of the Java standard library. So it is perfectly okay to use Map and Scanner together.
At current, the SO community's best guess is that you are using an IDE (like eclipse) that has a built-in console window/view. Under this assumption, it is assumed that you expect a black terminal/cmd window to open, however in most IDEs this is not the case. In eclipse the "console view" is where you will do your input. In Netbeans this will be the output window.

Related

How to run a program on standard input?

I've created an implementation of a Sokoban-solver and the code is currently looking like this (not going to post all the code):
public Sokoban() throws Exception{
myList = new ArrayList<Integer>();
file = new File("C:/Users/joaki/Desktop/sokoban/readin.txt");
sc = new Scanner(file);
sc.reset();
List<String> lines = new ArrayList<>();
while (sc.hasNextLine()) {
line = sc.nextLine();
As you can see I'm just using the filepath to be able to read the file with a scanner, but according to my assignment, it should be looking like:
To be more concrete if "map1.txt" is a file with a sokoban map your
agent program "agent" will get map1.txt sent to in on standard input.
Under unix/linux this corresponds to running the program like
agent < map1.txt
I don't understand really what they mean, am I supposed to run the program from the command-line argument or from the cmd?
Instead of the program reading a file, it should read them from user input - so yes, you should run the program from the command line. This means your program should get the input from System.in, not open a file directly:
sc = new Scanner(System.in);
When creating the Scanner use this:
sc = new Scanner(System.in);
It will tell the scanner to read from the default input.

Concatenate user input Strings to convert into a complete file path (Java)

I wrote a short script to create a file to my Desktop, and the file appeared. I just did it all in main, like so:
import java.io.*;
import java.util.Scanner;
public class FilePractice {
public static void main(String[] args) {
//create a new File object
File myFile = new File("/home/christopher/Desktop/myFile");
try{
System.out.println("Would you like to create a new file? Y or N: ");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
myFile.createNewFile();
}
else
{
//do nothing
}
}catch(IOException e) {
System.out.println("Error while creating file " + e);
}
System.out.println("'myFile' " + myFile.getPath() + " created.");
}
}
I just wanted to make sure the code worked, which it did. After that, I wanted to expand by creating a file with user input, as well as define which directory the user wished to send the file to. I'm on a Linux machine, and I wanted to send it to my Desktop again, so my user input was "/home/christopher/Desktop" for the userPath. Nothing happened. I even cd'd to my Desktop via terminal to "ls" everything there, and still nothing.
Perhaps my syntax is wrong?
If this is a duplicate of anything, my apologies. I tried to do a thorough search before coming here, but I only found info on creating files and sending files to directories that are already defined as a string (e.g. File myFile = new File("/home/User/Desktop/myFileName")).
Here is the expanded attempt:
try {
System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
String fileName = input.nextLine();
input.nextLine();
System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
String userFilePath = input.nextLine();
File userFile = new File(userFilePath, fileName);
System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
String userChoice = input.nextLine();
if (userChoice.equalsIgnoreCase("Y")) {
userFile.createNewFile();
//print for debug
System.out.println(userFile.getPath());
}
}catch(IOException e) {
System.out.println("Error while attempting to create file " + e);
}
System.out.println("File created successfully");
My print statement for a debug attempt outputs "/home/christopher/Desktop", but not the file name appended to the directory.
Thanks for any help offered. This is just for experimentation while learning Java I/O. Since a hypothetical user may not be on the same OS as me, I can work on those methods later. I'm keeping it on my home machine, hence the Unix filepath names.
Changing input.nextLine() to input.next() solved the problem. The program was not reaching the if statement after asking the user if they were sure their entered path was the desired save point.
I also put in a simple else statement that printed out ("File not created") to verify that it was skipping it.
Anyway, question answered. :-)

Why doesn't the console prompt for an input?

import java.io.*;
public class ConsoleDemo {
public static void main(String[] args) {
String str;
Console con;
con = System.console();
if (con == null)
return;
str = con.readLine("Enter a string : ");
con.printf("Here is your string %s", str);
}
}
I copied this code from the book, which says that I would get a prompt on the screen for entering a string, but my IDE just gives the message that the execution has termination, without giving me a prompt.
Eclipse nor Netbeans supports the use of Console. The Console.istty() method will return false and you will not have a console to use.
You can change your code to the following and achieve the same result and be able to run it from within the IDE.
import java.io.*;
public class ConsoleDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String and press enter");
System.out.println("You entered the String: " + scan.nextLine()
}
}
What IDE are you using? This code works just fine when you run it from the command line, so the problem clearly lies with the configuration of your IDE.
Use the following commands to compile and run your code from the command line:
javac ConsoleDemo.java
java ConsoleDemo
Edit: as this link suggests, using System.Console doesn't always work in IDEs. Alternatively you can just use System.in.
Your code is working from both Eclipse and Command Prompt.
Try this way as well if you are using Java 5 or +
Scanner in = new Scanner(System.in);
System.out.print("Enter a String : ");
String string = in.nextLine();
System.out.println("Here is your String : " + string);
By default, eclipse does not associate console with the JVM. You may have to configure it. But if you run it in command line, it will have console definitely and hence it will run without any problem.
It is because your IDE runs this code by javaw.exe (windowless -> no console) not java.exe (with console window) command, so System.console() returns null.
Standard solution is to read data from input stream which is represented by System.in so you can use for instance Scanner like
Scanner keybord = new Scanner(System.in);
String line = keybord.readLine();

how to handle a command-line input like "java.exe program < s1.in"

I know how to use string args to get the input from the command-line, and it is working fine with input = args[0] where my input is java.exe program s1.in
But I need to run a compare program in terminal. So my input must have the "<" symbol. However, then I can't get my input values using input = args[1]. When I type this in, the args.length become 0. Why does this happen?
As an aside, does anyone know how to best search for this kind of term in google? Itthink google does not recognize "<" in the search entry.
Thank you
It's because when you use xyzzy <inputfile, your shell runs xyzzy and "connects" that file to your standard input. It then expects you to read that standard input to get your data - you never see the argument because it's removed from the command line (or, more likely, never added to your argument list).
That's why many programs will process a file if given, otherwise they'll read their data from standard input. And that's exactly what you need to do here.
For doing this, you'll probably want something like:
import java.io.*;
class Test {
public static void main(String args[]) {
InputStreamReader inp = null;
Boolean isStdIn = false;
try {
if (args.length > 0) {
inp = new InputStreamReader(new FileInputStream(args[0]));
} else {
inp = new InputStreamReader(System.in);
isStdIn = true;
}
// Now process inp.
if (isStdIn)
inp.close();
} catch (Exception e) {
System.exit(1);
}
}
}
It selects either the file (if available) or the standard input stream for reading.
Often, the most easy way is to use Scanner:
Scanner scaner = new Scanner (System.in);

Masking password input from the console : Java

How to mask a password from console input? I'm using Java 6.
I've tried using console.readPassword(), but it wouldn't work. A full example might help me actually.
Here's my code:
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args)
{
Console console = System.console();
console.printf("Please enter your username: ");
String username = console.readLine();
console.printf(username + "\n");
console.printf("Please enter your password: ");
char[] passwordChars = console.readPassword();
String passwordString = new String(passwordChars);
console.printf(passwordString + "\n");
}
}
I'm getting a NullPointerException...
A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
You would use the Console class
char[] password = console.readPassword("Enter password");
Arrays.fill(password, ' ');
By executing readPassword echoing is disabled. Also after the password is validated it is best to overwrite any values in the array.
If you run this from an ide it will fail, please see this explanation for a thorough answer: Explained
Console console = System.console();
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");
If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:
# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"
jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}
# .. do something with 'password' variable ..
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"
See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"
The given code given will work absolutely fine if we run from console. and there is no package name in the class
You have to make sure where you have your ".class" file. because, if package name is given for the class, you have to make sure to keep the ".class" file inside the specified folder. For example, my package name is "src.main.code" , I have to create a code folder,inside main folder, inside src folder and put Test.class in code folder. then it will work perfectly.

Categories