Using Scanner to ask for your name [duplicate] - java

This question already has answers here:
How can I read input from the console using the Scanner class in Java?
(17 answers)
Closed 2 years ago.
I am working on a java assignment for class. Very basic but I just starting to learn to program and this is my first assignment. The assignment is to write a Java program that asks for your name and then greet you like “hello {name}” in java and I'm using online IDE- Browxy
This is my attempt and reads errors every time I run it.
code:
import java.util.Scanner;
class usersName {
public static void main(String[] args) {
String usersName;
System.out.print("Please enter your name: ");
usersName = java.util.Scanner;
System.out.println("Hello, " + usersName! ");
}
}

look for something like this :
`import java.util.Scanner;
class usersName {
public static void main(String[] args) {
try(Scanner scanner = new Scanner( System.in ))
{
String usersName;
System.out.print("Please enter your name: ");
usersName = scanner.next();
System.out.println("Hello, " + usersName+"! ");
}catch( Exception e){
System.out.println("you didn't take any name");
}
}
}`

Related

trouble getting rid of small error (symbol not found) in a little project java

I'm doing a small project and I have everything done, just one small error. the error shows "symbol not found" and shows the red squiggly line under my scan.
package pkgif.elsestatements.java;
import java.util.Scanner;
public class IfElseStatementsJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String your_name;
System.out.print("What is your name?");
your_name = user_input.next();
System.out.println("Hi " + your_name);
String user_input2;
System.out.print(".");
user_input2 = user_input.next();
System.out.println("Do you like Gospel Music Paul?"); //Asks question
String input = scan.nextLine(); //Waits for input
if (input.equalsIgnoreCase("Yes")) { //If the input is Yes)
System.out.println("Here are some songs; Amazing Grace, I'll Fly Away, A Little Talk With Jesus ");
}
else { //If the input is anything else
System.out.println("Ok! Have a nice day!");
}
}
this line is the one giving me trouble ---- String input = scan.nextLine(); //Waits for input
I was feeling really great about finish this with no errors beforehand, then this. Any help is appreciated.
According to the code above. You've defined Scanner user_input = new Scanner(System.in); i.e. user_input as the oject ref.
So, changing String input = scan.nextLine(); to String input = user_input.nextLine(); should do.

How do I check two inputs against the key and value of a hashmap? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I am just learning HashMaps, and have just written my first program using them. For some reason, my check to determine if the inputs I've entered match up with the key and it's corresponding value always returns false. Can anyone tell me why that is?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) throws FileNotFoundException {
HashMap<String, String> userPass = new HashMap<String,String>();
HashMap<String, String> userFull = new HashMap<String, String>();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the filename to read from: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
String fullname=inputFile.next()+" "+inputFile.next();
String username=inputFile.next();
String pass=inputFile.nextLine();
userPass.put(username, pass);
userFull.put(username, fullname);
}
inputFile.close();
//initialize variable for use after loop
String inputUsr = null;
//checks if key/value is found
boolean b=false;
int tries=1;
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.next();
System.out.print("\nPassword: ");
String inputPass=keyboard.next();
//if inputted password equals the password of the inputted username
if(inputPass.equals(userPass.get(inputUsr)))
b=true;
System.out.println("Either the username or password is incorrect. You have "+(3-tries)+" more attempts.");
tries++;
//program quits afte 3 tries
if(tries>3){
System.exit(0);
}
}
System.out.println("Welcome "+userFull.get(inputUsr));
}
}
There are two problems in the code inside your while loop as explained below:
(1) keyboard.next() is reading the console output text i.e., reading the printed text 'Password', so replace keyboard.next() with keyboard.nextLine();
(2) You did not handle the else condition for the tries count
You can refer at the below code with inline comments:
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.nextLine();
System.out.print("\nPassword: ");
String inputPass=keyboard.nextLine();
if(inputPass.equals(userPass.get(inputUsr))) {
b=true;
} else {
System.out.println("Either the username
or password is incorrect.
You have "+(3-tries)+" more attempts.");
tries++;
}
if(tries>3){
System.exit(0);
}
}

Checking if a file contains number that the user has entered (java) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a .txt file in here "C:\failass.txt". It contains the following info:
AA051245445454552117989
LT647044001231465456
LT517044077788877777
LT227044077788877777
CC051245445454552117989
I have found a code which scans if the user input matches the info contained in the file:
package ibanas;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class ReadFromFile {
public static void main(String[] args) throws IOException {
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine();
if(isFound(number)){
System.out.println("The number "+number+ " is there");
}else{
System.out.println("The number "+number+ " doesn't exist");
}
}
public static boolean isFound(String number) {
Scanner sc = new Scanner(ReadFromFile.class.getResourceAsStream("C:\failass.txt"));
String word="";
while (sc.hasNextLine()) {
word = sc.next();
if (word.equals(number.trim())) {
return true;
}
}
return false;
}
}
But when i enter (for example) this line AA051245445454552117989 it gives me the following error:
What number would you like to check for?
AA051245445454552117989
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at ibanas.ReadFromFile.isFound(ReadFromFile.java:24)
at ibanas.ReadFromFile.main(ReadFromFile.java:15)
Thanks for any advice :)
the arg for the scanner, namely ReadFromFile.class.getResourceAsStream("C:\failass.txt") returns null. probably because you need to escape the backslash with another "C:\\failass.txt"

JAVA - Newbie trying to get user input

I am an extreme beginner in Java and I can't seem to get the user input. I am using eclipse mars. My code:
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("What is your name?");
Scanner UserName = new Scanner(System.in);
System.out.println(UserName);
}
}
You need to first create your Scanner, then call nextLine on it to get input from the user:
import java.util.Scanner;
class NameAsker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("What is your name? ");
String userName = input.nextLine();
System.out.println("Your name is: " + userName);
}
}
try
System.out.println(UserName.nextLine());
Read Oracle docs for more info
you can use like.
Scanner input=new Scanner(System.in);
if you want to get integer.
int number=input.nextInt();
System.out.Println(number);
for String:
String str=input.nextLine();
There are other method for taking user input like bufferedReader and BufferedInputStream for more details check Java Docs.

How to have my code run until I enter a number

I'm sorry if this is a silly question but I am fairly new to coding and so for my assignment I was given this code:
package webservice;
import webservice.Weather;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the zip code : ");
java.lang.String zipCode = scan.nextLine();
try{
webservice.Weather service = new webservice.Weather();
webservice.WeatherSoap port = service.getWeatherSoap();
webservice.WeatherReturn result = port.getCityWeatherByZIP(zipCode);
System.out.print(result.getCity()+ " ");
System.out.println (result.getState());
System.out.println("Zip code " + zipCode);
System.out.println ("Current Temperature is " + result.getTemperature());
}
catch (Exception ex){
System.out.println("Error");
}
}//end main
}//end class
The code runs perfectly fine but I have to have it loop until i enter "0" for the zip code.
I'm fairly new to coding and I tried to review my previous works to try to incorporate a loop but I was never successful. Which loop would be the most efficient to have the code loop until the user enters "0" as the zip code?
Simply try this:
Scanner scan = new Scanner (System.in);
int zipCode;
while(scan.nextInt()!=0){
System.out.print ("Enter the zip code : ");
zipCode = scan.nextInt();
}
Use a while loop to verify your condition and use .nextInt() to get an int from the scanner.
Also there's a typo:
If you use :
import webservice.Weather;
You don't have to do this:
webservice.Weather service = new webservice.Weather();
It's simply:
Weather service = new Weather();
Take a look at Using Package Members for further information.
How about while loop?
String zipCode;
while(!"0".equals(zipCode = scan.nextLine())) {
//to do rest
}
Sample code:
import java.util.Scanner;
class Ideone
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String zipCode;
while(!"0".equals(zipCode = sc.nextLine())) {
System.out.printf("zip code: %s\n", zipCode);
}
System.out.printf("last zip code: %s\n", zipCode);
}
}
I/P:
123
456
789
0
O/P:
zip code: 123
zip code: 456
zip code: 789
last zip code: 0
while loop would do your trick.
This is because while loop checks the condition first and then iterates over if the condition is found to be true. And in your case we need to check if the user has entered the correct value or not. If he has entered 0 we do not need to proceed further.

Categories

Resources