Getting an input from the user console - Java code [duplicate] - java

This question already has answers here:
Java: How to get input from System.console()
(9 answers)
Closed 8 years ago.
What is a Java equivalent for this C++ code snippet:
string str ;
while(cin>>str){
//code
}

Something like this
String str ;
while((str = System.in.readLine()) != null){
//code
}

Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();

Scanner scanner = new Scanner(System.in);
boolean flag = true;
while(flag)
{
String str = scanner.nextLine();
// Add any condition to set flag = false to exit from while loop
}

you can do it either with a GUI style .
import javax.swing.JOptionPane;
String Input=JOptionPane.showInputDialog("Title","Message");

Related

How to replicate this Python code in Java? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
NoSuchElement exception when using Scanner
(2 answers)
Closed 1 year ago.
This is a silly game written in Python, I was wondering how to reproduce it in Java:
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')
Basically, it requests to write the string "your name" to break the while loop, now, I've tried this code in Java but it throws an error:
import java.util.Scanner;
public class sillyGame {
public static void main(String [] args) {
String name = "";
while (name != "your name"){
System.out.println("Please type your name");
Scanner input = new Scanner(System.in);
name = input.next();
input.close();
}
System.out.println("thank you");
}
}
The error is: "Exception in thread "main" java.util.NoSuchElementException"
I really appreciate your help.

Java IO Console [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am working on a login for my USB. I know there are other languages that do that better but I am learning Java. I get an error using the IO Console
package access;
import java.awt.Desktop;
import java.io.*;
public class access {
public static void main(String[] args)throws IOException {
BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));
Console c = System.console();
Desktop desktop = Desktop.getDesktop();
File dirToOpen = null;
String user = c.readLine("Username: ");
char pass[] = c.readPassword("Enter password: ");
String uPass = new String(pass);
if(user.equals("yuto") && uPass.equals("abascalesgay")) {
try {
dirToOpen = new File("E:\\encrypted");
desktop.open(dirToOpen);
}
catch (IllegalArgumentException iae) {
System.out.println("File Not Found");
}
}
else {
System.out.println("Credenciales no vĂ¡lidas we, vuelve a intentarlo.");
}
}
}
Error log
Exception in thread "main" java.lang.NullPointerException at
access.access.main(access.java:17)
If you will add this code to your program:
if(c == null)
{
System.out.print("No console available");
return;
}
you will check if your line Console c = System.console(); returns NULL or not.
Currently it is returning NULL as no console was found and the rest of the code can't compile because of it.
If you are running your program through some IDE - it will not work as IDE is not a console!
Go to "cmd.exe"
type "cd" - hit enter..
now type "java " - hit enter
Another alternative to creating your own BufferedReader object from System.in is to use java.util.Scanner like this:
import java.util.Scanner;
Scanner in;
in = new Scanner(System.in);
String s = in.nextLine();
Also if you want to use the System.console() you shouldn't get password with char pass[] but do it through:
String username = console.readLine("Username: ");
String password = new String(console.readPassword("Password: "));

how i can save multiple lines inside a string in java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
user have to write an email in multiple lines and stop the input when ".." (two dots) are entered by the user. then the email should be saved to the variable but the variable saves the last input which are the two dots.
this is my code
any changes?
BufferedReader inl = new BufferedReader(new InputStreamReader(System.in));
String email_data;
System.out.println("Data: ");
do{
email_data = inl.readLine();
} while(email_data != "..");
Append the input to your variable instead of overriding it.
Also, don't use '!=' or '==' on Strings - use the .equals() method instead.
BufferedReader inl = new BufferedReader(new InputStreamReader(System.in));
String email_data = "";
String input;
System.out.println("Data: ");
do{
input = inl.readLine();
if (!input.equals("..")) {
email_data += input;
}
} while(!input.equals(".."));

Weird Behaviour with the java scanner utility [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I'm not sure how dumb I am or if I am missing something quite simple; anyhow, I am trying to get a basic username and password input from the user using the scanner utility.
I have made sure scanner was initialised correctly (Scanner sc = new Scanner(System.in)
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
The issue I am having is when I run this part of the code (above), the output I get looks like this (below) where I start inputting into the password section. Its as though it is just skipping over the first call to the scanner.
Username or Email:
Password: (this is where my input goes)
My only guess is that the scanner is taking the second printing as its input but I am not sure so any help is greatly appreciated.
p.s I will leave the entire method at the bottom incase it helps.
Thanks.
public static void loginPage() throws SQLException{
int requestCounter = 0;
do {
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
boolean validLoginRequest = accountLoginCheck(username, password);
if (validLoginRequest) {
break;
} else {
requestCounter++;
}
} while (requestCounter < 3);
if (requestCounter == 3) {
System.out.println("Too many attempts");
return;
}
System.out.print("TO MAIN MENU");
Remove \n from System.out.print("\nPassword: ");
Username or Email: myemail
Password: pass

Parse string in Java [duplicate]

This question already has answers here:
string parsing in java
(4 answers)
Closed 7 years ago.
I have a string in below format
// JCSDL_MASTER b04591342ee71a2baa468d9d2a340ec8 AND
// JCSDL_VERSION 1.0
// JCSDL_START 0980a5f2ef935c4ed153bf975879eac0 twitter.text,contains_any,27-52
twitter.text contains_any "obama, santorum, gingrich, romney, ronpaul, ron paul"
// JCSDL_END
AND
// JCSDL_START f7c18a6fedd90c6b4d77acc14a3a8e5c interaction.type,in,21-29
interaction.type in "twitter,facebook,digg,youtube"
// JCSDL_END
// JCSDL_MASTER_END
I suppose it include newline character at the end, i need to just get only those line which is not being started by // how to get only those lines?
Pretty simply, just split up the string into individual lines (note: \n is an escape character for a line break), then only use each line if it does not start with //
String[] lines = string.split("\\n");
for (String line : lines)
{
if (!line.startsWith("//"))
{
//use the line and do your thing
}
}
Use Scanner.nextLine() to read each line and then Ignore the ones which starts with // like following:
String str = "hi \n//this is kuleep\nthis is a test class";
Scanner sc = new Scanner(str);
while (sc.hasNextLine()) {
String line = sc.nextLine();
if(!line.startsWith("//"))
{
System.out.println(line);
}
}

Categories