I have a project that involves me to create a program that reads the user input and the program then tells them what zone they are in, but I cant seem to how to add multiple strings.
import java.util.*;
public class hello {
public static void main (String args[]){
Scanner input = new Scanner (System.in);
String answer = input.nextLine();
// I would like more stations to be added but I don't no how
if ("Mile End".equals(answer)) {
System.out.println( input +" is in Zone 2");
} else {
System.out.println("That is not a Station, please try again");
}
}
}
It seems like you want a loop. One such option, would be to stop when the user enters a special "zone" (like quit below).
String answer = input.nextLine();
while (!answer.equalsIgnoreCase("quit")) {
// I would like more stations to be added but I don't no how
if ("Mile End".equals(answer)) {
System.out.println( input +" is in Zone 2");
} else {
System.out.println("That is not a Station, please try again. "
+ "Quit to stop.");
}
answer = input.nextLine();
}
am not entirely sure what you mean by "but I cant seem to how to add multiple strings." but you seem to print the Scanner object " System.out.println( input +" is in Zone 2");" instead of the answer
System.out.println( answer +" is in Zone 2");
Could it be because of this you are not seeing the expected result ?
public static void main (String args[]){
Scanner input = new Scanner (System.in);
String answer = input.nextLine();
if (answer.equals("Mile End")) { // i would like more stations to be added but i dont no how
System.out.println( answer +" is in Zone 2");
} else {
System.out.println("That is not a Station, please try again");
}
}
You may need an else if statement
import java.util.*;
public class hello {
public static void main (String args[]){
Scanner input = new Scanner (System.in);
String answer = input.nextLine();
if ("Mile End".equals(answer)) {
System.out.println( answer+" is in Zone 2");
} else if("Hobbitland".equals(answer) {
System.out.println( answer +" is in Zone 42");
} else
System.out.println("That is not a Station, please try again");
}
}
}
Alternatively you could use a switch like:
import java.util.*;
public class hello {
public static void main (String args[]){
Scanner input = new Scanner (System.in);
String answer = input.nextLine();
switch(answer){
case "Mile End":
System.out.println( answer +" is in Zone 2");
break;
case "Hobbitland":
System.out.println( answer +" is in Zone 42");
break;
default:
System.out.println("That is not a Station, please try again");
break;
}
}
}
There are still other means to solve this problem without the need of such a complex control structure. Just create a Map that holds your station names as key and their zone as value. When you get an input you just look it up in your map and retrieve its zone. If it's not in your map you print your error message.
Why not create a map where the zone is the key and the value is a list of stations that come under that zone?
You can then have a method that handles the population of the map...
private static Map<String, List<String>> createZoneMap() {
Map<String, List<String>> zoneMap = new HashMap<String, List<String>>();
// Probably want to populate this map from a file
return zoneMap;
}
Then your main can look something like...
public static void main(String args[]) {
Map<String, List<String>> zoneMap = createZoneMap();
Scanner scan = new Scanner(System.in);
String input;
while (true) {
input = scan.nextLine();
// Some code to exit the application...
if (input.equalsIgnoreCase("quit")) {
System.out.println("Exiting...");
System.exit(1);
}
String zone = findZone(zoneMap, input);
if (zone != null) {
System.out.println(input + " is in " + zone);
} else {
System.out.println("That is not a Station, please try again");
}
}
}
Then when you type in the station name you look through the map to find the zone which the station comes under, if its not present then return null or something
private static String findZone(Map<String, List<String>> zoneMap, String station) {
// Maybe make this more versatile so that it does not care about case...
for (Map.Entry<String, List<String>> entry : zoneMap.entrySet()) {
if (entry.getValue().contains(station)) {
return entry.getKey();
}
}
return null;
}
Hope that's a good starting point for you. You could also consider moving away from performing all of your logic in the main method and instead create an instance of your class in the main.
Related
This is the Question: Create an array of Strings and assign 5 names to it. Ask the user what their name is, if their name is the same as one that is already in the list do something. Get creative!, use a for-each loop to print every name in the array with a space in-between each indices.
This is what I have so far. One of the issues I am having is that the scanner is only comparing the input to the first name on the array and not the rest.
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
}
else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
break;
}
}
}
Feel free to comment on any other issues you see. I am new at this and I'd appreciate an feedback. Thx
Maybe this will be helpful. I think the "break" is called prematurely. There are lots of ways you can solve this, but I used a boolean to determine if the name was found. Then I used the boolean after the loop to determine what to print.
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
boolean isFound = false;
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
isFound = true;
break;
}
}
if (isFound) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
} else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
}
Same method but slightly different :)
`import java.util.Scanner;
import java.util.ArrayList;
public class New {
public static void main (String[]args) {
String [] cities = {"Poznan", "Warsaw", "Gdansk", "Wroclaw", "Krakow", "Lodz", "Katowice"};
Scanner scan = new Scanner(System.in);
System.out.println("What is the name of your city in Poland? ");
String name = scan.nextLine();
for (String n:cities) {
if (n.equalsIgnoreCase(name)) {
System.out.println("You are citizen of Poland from " +name);
System.out.println("Thank your for visiting " +name);
}
else {
System.out.println("You are not from Poland!!!" );
System.out.println("There is not city in Poland called" +name);
}
break;
}
}
}`
Using my code I am trying to tell the user to enter not to enter a string until the user an integer but while running the program it is infinite.
public static void main(String[] args) {
int age = 1;
Utilisateur utilisateur = new Utilisateur();
Scanner u = new Scanner(System.in);
System.out.println("Enter your Name: ");
utilisateur.setNom(u.nextLine());
System.out.println("Enter your Surname: ");
utilisateur.setPrenom(u.nextLine());
System.out.println("Enter your Matricule: ");
utilisateur.setMatricule(u.nextLine());
System.out.println("Enter your Sexe: ");
utilisateur.setSexe(u.nextLine());
do {
try {
System.out.println("Enter your Age: ");
utilisateur.setAge(u.nextInt());
System.out.println(utilisateur.detail());
age = 2;
} catch (Exception e) {
System.out.println("Enter a valid age ");
}
}
while (age == 1);
}
}
Okay, so let's start by cleaning up the code a bit. The whole "age" variable is a bit weird. It seems like it's containing some status on whether or not you've read the age. But that's kind of boolean, isn't it? So let's redo the code with that in mind. I'll change the do-while to a simple while first, but we can change it back afterwards. Furthermore, it might be a good idea to rename "u" to "keyboard", or "clavier" if you prefer french.
public static void main(String[] args) {
Utilisateur utilisateur = new Utilisateur();
Scanner clavier = new Scanner(System.in);
System.out.println("Enter your Name: ");
utilisateur.setNom(clavier.nextLine());
System.out.println("Enter your Surname: ");
utilisateur.setPrenom(clavier.nextLine());
System.out.println("Enter your Matricule: ");
utilisateur.setMatricule(clavier.nextLine());
System.out.println("Enter your Sexe: ");
utilisateur.setSexe(clavier.nextLine());
boolean hasEnteredAge = false;
while(!hasEnteredAge) {
System.out.println("Enter your Age: ");
String ageInput = clavier.nextLine().trim(); // remove leading and trailing whitespace. " 21 " becomes "21".
try {
int age = Integer.parseInt(ageInput);
utilisateur.setAge(age);
System.out.println(utilisateur);
hasEnteredAge = true;
} catch (Exception e) {
System.out.println("Enter a valid age.");
}
}
}
}
Notice that I moved the variable to the beginning of the loop, which is where we need to know about this fact, and how we initialized it to false. We now have to set it to be true afterwards.
But there is a bit more to do here I think. We have a bunch of prints, followed by inputs. Surely, this can be farmed out to a method, that makes this look a bit nicer? But before we do that, we should take another look at the loop. We can do the loop in a multitude of ways. We can do
do {
System.out.println("Enter your Age: ");
String ageInput = clavier.nextLine().trim(); // remove leading and trailing whitespace. " 21 " becomes "21".
try {
int age = Integer.parseInt(ageInput);
utilisateur.setAge(age);
System.out.println(utilisateur);
break; // this means that we should exit the loop
} catch (Exception e) {
System.out.println("Enter a valid age.");
}
}while(true); // So if we ever get here, we're not done.
Here, we're relying on the break to get us out of the loop. This works, but personally I don't like it. It's not a wrong thing to do however, so I'll just leave it in. You can also have it like the old do-while loop:
boolean hasEnteredAge = false;
do {
System.out.println("Enter your Age: ");
String ageInput = clavier.nextLine().trim(); // remove leading and trailing whitespace. " 21 " becomes "21".
try {
int age = Integer.parseInt(ageInput);
utilisateur.setAge(age);
System.out.println(utilisateur);
hasEnteredAge = true;
} catch (Exception e) {
System.out.println("Enter a valid age.");
}
} while (!hasEnteredAge);
Whichever you choose though, it's fine.
Now let me just tackle the issue of the printlines and reads:
If you add a method "prompt" that takes a prompt and returns a string, you can simplify this down quite handily like so:
public class EnterNameHere {
private static Scanner clavier = new Scanner(System.in);
public static String prompt(String prompt) {
System.out.println(prompt);
return clavier.nextLine().trim();
}
// ... The rest is as before.
}
Now, the reading in part becomes very simple:
public static void main(String[] args) {
Utilisateur utilisateur = new Utilisateur();
utilisateur.setNom(prompt("Enter your Name: "));
utilisateur.setPrenom(prompt("Enter your surname: "));
utilisateur.setMatricule(prompt("Enter your matricule: "));
utilisateur.setSexe(prompt("Enter your sex: "));
And an important question arises: If we are to do this for string inputs, why not for integer (int) inputs as well?
I propose:
public static int promptInt(String prompt) {
String value = prompt(prompt);
try {
return Integer.parseInt(value);
} catch(NumberFormatException ignored) {
System.out.println("Invalid number: '" + value + "'");
return promptInt(prompt); // We try again!
}
}
Notice if you would be so kind, that if calling the method promptInt doesn't work, we print an error message and just try again. This will only work for a few hundred times before it all crashes, but that should be enough. (You can of course adapt the while-loop approach from earlier if you don't want that to happen.) This trick of a method or function calling itself multiple times until the work is done is called "recursion" and it is as powerful as looping is. It can be confusing to people who are new to programming, but I think this example is straightforward. If it isn't, you can simply substitute the whole loop thing as mentioned. Of course, there is one method called prompt, and another called promptInt. To avoid any confusion we rename the prompt-method to promptString, and the entire program simply becomes:
public class YourNameHere {
private static final Scanner clavier = new Scanner(System.in);
public static String promptString(String prompt) {
System.out.print(prompt);
return clavier.nextLine().trim();
}
public static int promptInt(String prompt) {
String value = promptString(prompt);
try {
return Integer.parseInt(value);
} catch(NumberFormatException ignored) {
System.out.println("Invalid number: '" + value + "'");
return promptInt(prompt); // We try again!
}
}
public static void main(String[] args) {
Utilisateur utilisateur = new Utilisateur();
utilisateur.setNom(promptString("Enter your Name: "));
utilisateur.setPrenom(promptString("Enter your surname: "));
utilisateur.setMatricule(promptString("Enter your matricule: "));
utilisateur.setSexe(promptString("Enter your sex: "));
utilisateur.setAge(promptInt("Enter your age: "));
System.out.println("You have created an utilisateur: " + utilisateur);
}
}
Plus the definition of Utilisateur of course.
I think this is a much simpler way to do it, by creating methods that does the boring work for you, you can read the code in the main method and immediately understand what is going on. If you need to understand how, you can go up and look at the helping prompt-methods.
You should add u.nextLine(); in catch block in order to skip invalid value entered in the scanner.
public class Main {
public static void main(String[] args) {
System.out.println("Please enter a math value.");
Scanner sayiyaz = new Scanner(System.in);
if(sayiyaz.hasNextInt()) {
int sayi1 = sayiyaz.nextInt();
}
else {
System.out.println("I wish u could know what is a math value .");
}
}
}
In the else block of code i want to restart the "main" method from the beginning and ask the same question.
But how to do that ?
You can call it if you want to (like Sudhakar sugested) but i assume that you just want to request the input until you get something that fits your needs in that case you have a better solution
public static void main(String[] args) {
boolean done = false;
Integer sayi1 = null;
do {
System.out.println("Please enter a math value.");
Scanner sayiyaz = new Scanner(System.in);
if (sayiyaz.hasNextInt()) {
sayi1 = sayiyaz.nextInt();
done = true;
} else {
System.out.println("Input is wrong ");
}
} while (!done);
System.out.println("Here is youre input " + sayi1);
}
The answer is that you don't want to restart main. This is the entry point used by the Java Virtual machine to start your application. The simplest way to do what you want is to use a loop, so something like:
while (true) {
System.out.println("Please enter a math value");
// The rest of your code.
if (finished)
break;
}
In my code, I want the loop to exit if the user enters an empty string for either variables. Nothing seems to work after I enter an empty string.
Where am I going wrong?
import java.util.HashMap;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String lakeName;
String timeRun;
HashMap<String, Double> newMap = new HashMap<>();
do {
System.out.println("Enter the Lake Name");
lakeName = input.nextLine();
System.out.println("Enter number of minutes run");
timeRun = input.nextLine();
Double finalRun = Double.parseDouble(timeRun);
newMap.put(lakeName, finalRun);
if(lakeName.equalsIgnoreCase("") || timeRun.equalsIgnoreCase("")){
break;
}
} while(true);
for(String key: newMap.keySet()){
Double value = newMap.get(key);
System.out.println(key + ": "+ value);
}
}
}
try this :
do {
System.out.println("Enter the Lake Name");
lakeName = input.nextLine();
System.out.println("Enter number of minutes run");
timeRun = input.nextLine();
if(lakeName.equalsIgnoreCase("") || timeRun.equalsIgnoreCase("")){
break;
}
Double finalRun = Double.parseDouble(timeRun);
newMap.put(lakeName, finalRun);
} while(true);
put the if{...} up, if not , it will be given NumberFormatException.
One way to do is to check if String is isEmpty(), put a break statement.
So in your case it would be like:
if(lakeName.isEmpty())
break;
You gotto do the same thing with timeRun variable;
When you enter an empty string for the timeRun, you will try to parse an empty string as double. This fails and throws this exception:
java.lang.NumberFormatException: empty String
You can solve this by placing the following code into the loop:
System.out.println("Enter the Lake Name");
lakeName = input.nextLine();
System.out.println("Enter number of minutes run");
timeRun = input.nextLine();
if (lakeName.equalsIgnoreCase("") || timeRun.equalsIgnoreCase("")) {
break;
}
Double finalRun = Double.parseDouble(timeRun);
newMap.put(lakeName, finalRun);
I just moved the break up a few lines, including its condition.
Also, you can replace the .equalsIgnoreCase("") by .isEmpty(), as already stated in the other answer.
when i type what is stored inside the string variables b and p, it does not respond until I have clicked the enter key several times.
After this point the program only prints out what is inside the else statement.
The only string variable that the program is responding to is j.
The code:
package legit;
import java.util.Scanner;
public class Gamee {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String j = "good, how are you?";
String b = "good";
String p = "bad";
System.out.println("Hello, my name is Julie the Robot");
System.out.println("How Are You?");
if (j.equals(sc.nextLine())) {
System.out.println("Im Doing Great!");
}else if (b.equals(sc.nextLine())) {
System.out.println("Thats Great! :)");
}else if (p.equals(sc.nextLine())){
System.out.println("Thats not good");
}else {
System.out.println("I see...");
}
Do you know that every time you use sc.nextLine() you are asking user for new input?
Try maybe using it once before your ifs and store received input in value, then use that value in conditions.