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

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.

Related

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: "));

Unable to read MySQL log file [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 4 years ago.
Hey I am trying to read any "root" string in the log file name "SHIKHAR.log" but the compiler keeps on showing.
dam.java:12: error: cannot find symbol
System.out.println("I found in file " +SHIKHAR.getName());
^
symbol: variable SHIKHAR
location: class dam
1 error
I am not sure what's wrong with it I have tried appending the extensions and try it otherwise aswell but it doesn't work.
import java.util.Scanner;
import java.io.*;
class dam
{
public static void main (String arg[])
{
final Scanner scanner = new Scanner("SHIKHAR");
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains("root")) {
// a match!
System.out.println("I found in file " +SHIKHAR.getName());
break;
}
}
}
}
You are using undefined variable name SHIKHAR.
System.out.println("I found in file " +SHIKHAR.getName());
As per your assumption SHIKHAR is file but here in your code its just a string literal.
You can define a variable as
final File SHIKHAR = new File("SHIKHAR");
final Scanner scanner = new Scanner(SHIKHAR);
BTW, as per your current code will simply read string and not from file named SHIKHAR.
final Scanner scanner = new Scanner("SHIKHAR");

Exception in thread "main" java.util.NoSuchElementException: No line found 3 [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
In this code, throws me this exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.cristianvalero.filetransfers.main.client.Client.askToDo(Client.java:98)
at com.cristianvalero.filetransfers.main.client.Client.run(Client.java:64)
at com.cristianvalero.filetransfers.main.client.Client.main(Client.java:36)
Method that throws the error:
private String askToDo()
{
Scanner teclado = new Scanner(System.in);
System.out.print("What would you like to do? [help]: ");
String a = teclado.nextLine().toLowerCase();
teclado.close();
return a;
}
But in this code that executes before the other code, no throws any error.
private void setConnection() //Type of bookmarks "servers":["casa:1.1.1.1:3306", "trabajo:1.1.1.1:7809"]
{
Scanner teclado = new Scanner(System.in);
System.out.print("New server [N] or Connect previous server [P]: ");
final String typed = teclado.nextLine().toLowerCase();
if (typed.equals("n"))
noHaveServers(teclado);
else if (typed.equals("p"))
{
if (ServerList.getAllServers(CONFG).size() == 0)
noHaveServers(teclado);
else
haveServers(teclado);
}
else
{
System.out.println("Sorry, I can't understand you.");
teclado.close();
setConnection();
}
teclado.close();
}
PD: This methods are in the Client class that is extended of Thread and are called from the run() method.
Don't close the Scanner teclado in setConnection(). Closing a Scanner also closes its associated stream. Then in askToDo, when you create another Scanner, System.in is already closed.
You should have a single top-level static Scanner object, initialized with System.in, and use that everywhere in your class instead of creating a new Scanner in each method.

Java reading out data from Console with Scanner goes wrong in extended Class [duplicate]

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 7 years ago.
I have the following Classes:
public class Human {
private String firstName;
private String lastName;
public Human(){
Scanner in = new Scanner(System.in);
System.out.println("Please enter Firstname");
setFirstName(in.nextLine());
System.out.println("Please enter Lastname");
setLastName(in.nextLine());
in.close();
}
}
And
public class Customer extends Human{
private long customerNumber;
private String customerCompanyName;
static long customerNumberCounter = 0;
public Customer(){
super();
Scanner in = new Scanner(System.in);
setCustomerNumber(customerNumberCounter);
customerNumberCounter ++;
System.out.println("Please enter Companyname");
setCustomerCompanyName(in.nextLine());
in.close();
}
}
When i call the following Main Method:
public static void main(String[] args) {
Customer aCustomer = new Customer();
System.out.println(aCustomer.giveFullName());
}
The Programm throwes the following Error:
Exception in thread "main" java.util.NoSuchElementException: No line
found at java.util.Scanner.nextLine(Unknown Source) at
customers.Customer.(Customer.java:17) at
customers.Customer.main(Customer.java:22)
I don't understand what I am doing wrong, since I can create an Object of Class Human without any problems but when I create a Customer, the Error pops up directly after entering the LastName in the Human Constructor.
I already renamed the Scanner and so on but that didn't solve the problem.
Anybody got a Solution for this?
Before read the next,you close the scanner.So it can not read the line:
public Human(){
Scanner in = new Scanner(System.in);
System.out.println("Please enter Firstname");
setFirstName(in.nextLine());
System.out.println("Please enter Lastname");
setLastName(in.nextLine());
//in.close();
}

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

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");

Categories