Switching String to Integer - java

I need the syntax for adding in the variable parameter to a switch case that already has lots of parameters. The context is provided below.
I'm using a switch case to change a string answer to an integer return. Instead of having the user answer
1. This.
2. Something else.
I want the answer to look like
(y/n)
I've done it before with a code like this:
static public int getYN() {
String answer = "";
switch(keyboard.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
And then using the statement:
int getAnswer = getYN();
System.out.println();
if (getAnswer == 1) {
System.out.println("Stuff.");
test = 1;
}
else {
System.out.println("Other stuff.");
System.out.println();
}
But, I don't know where to put the String answer variable into the switch case. Usually, if you aren't using many other parameters, it would just be
switch(answer) {
}

Check it inline, forget having a dedicated method to doing this check.
char getAnswer = keyboard.next().charAt(0);
System.out.println();
if (getAnswer == 'y' || getAnswer == 'Y')
{
System.out.println("Stuff.");
test = 1;
}
else if( getAnswer == 'n' || getAnswer == 'N')
{
System.out.println("Other stuff.");
System.out.println();
}
If you absolutely have to use a switch:
char getAnswer = keyboard.next().charAt(0);
switch(getAnswer)
{
case 'y':
System.out.println("Stuff.");
test = 1;
break;
case 'n':
System.out.println("Other stuff.");
System.out.println();
break;
}

You can achieve the same thing in one line:
public static int getYN(String s) {
return ("yn YN".indrxOf(s) + 3) % 3;
}
Both upper and lower cases are handled, and the "not found" default value of 2 is handled by adding 3 (indexOf() returns -1 when the target is not found) and modulus divusion takes care of the capital letter indexes.
Fairly neat even if I do say so myself.

Related

How can I translate a keyboard press to a value in my Java program?

In a text adventure game written in Java, I want the character race to be as follows( the number corresponds to the key the user types):
// Character Race
// 1) Human
// 2) Dwarf
// 3) Elf
// 4) Orc
How do I write that out to the player?
Like this?
So I ask the user which race they want:
System.out.print("Enter character race: ");
charRace = input.nextInt();
System.out.println("Your character's race is " + charRace);
How do I tell my program that 1 = Human, 2 = Dwarf, etc...??
Do I need to create a dictionary or something similar?
Thanks!
This might be a little out of the range of scope, but for me, when you have a limited range of possible values, I'd tend to look towards using a enum
enum Race {
HUMAN(1), DWARF(2), ELF(3), ORC(4);
private int value;
private Race(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static Race from(int value) {
for (Race race : Race.values()) {
if (race.getValue() == value) {
return race;
}
}
return null;
}
}
Then you can do fun things like...
Race race = Race.from(1);
if (race == null) {
System.out.println("Invalid selection");
} else {
switch (race) {
case DWARF:
System.out.println("Gunghrim Dwarf!");
break;
case ELF:
System.out.println("Welcome Elf!");
break;
case HUMAN:
System.out.println("Welcome Human!");
break;
case ORC:
System.out.println("Welcome Orc!");
break;
}
}
You could even automate the menu. Start by adding something like...
public String getProperName() {
StringBuilder sb = new StringBuilder(32);
String name = name();
sb.append(name.charAt(0));
sb.append(name.substring(1).toLowerCase());
return sb.toString();
}
to the Race enum and then you could create a menu doing something like...
List<Race> races = Arrays.asList(Race.values());
races.sort(new Comparator<Race>() {
#Override
public int compare(Race o1, Race o2) {
return o1.getValue() - o2.getValue();
}
});
for (Race race : races) {
System.out.println(race.getValue() + ") " + race.getProperName());
}
which prints
1) Human
2) Dwarf
3) Elf
4) Orc
Have a look at the enums type trail for more details
You could just use some if statements to identify the entered race. Something like this
if(charRace == 1){
String race = "Human";
} else if(charRace == 2){
String race = "Dwarf";
} else if(charRace == 3){
String race = "Elf";
} else{
String race = "Orc";
}
Maybe not the most efficient way to do this though.
If you are just using integers wouldn't a simple Array be the better choice?
String races[] = {"Dwarf","Elf","Human","Orc"};
System.out.println("You selected: "+races[charRace]);
edit:
If you want error handling:
String races[] = {"Dwarf","Elf","Human","Orc"};
if(charRace>=0&&charRace<races.length)
System.out.println("You selected: "+races[charRace]);
else
System.out.println("Error: invalid input!");
Also it is definetely more efficient to use a switch case over an if-else!
Here is an example, althought I dont recommend it since you are handling integers!!
switch (charRace) {
case 1:
System.out.println("You selected Dwarf");
break;
case 2:
System.out.println("You selected Elf");
break;
case 3:
System.out.println("You selected Human");
break;
case 4:
System.out.println("You selected Orc");
break;
default:
System.out.println("Error: invalid input!");
break;
}
If you want this program more sustainable, you should use inherithence.
Like:
public class Orc extends Race{
}
public class Human extends Race{
}
After creation of the all races, you can create a method for creating new race for given number.
For example:
public static Race createRace(int raceType){
if(raceType == 1)
return new Orc();
else if(raceType == 2)
return new Human();
}
Also, you can define different variables and different methods for your races.

An option in my do-while to print out all 3 conditions

String xdd="";
Scanner Lenijs = new Scanner(System.in);
do {
System.out.println("Starting number a: ");
int a = Lenijs.nextInt();
System.out.println("Ending number b: ");
int b = Lenijs.nextInt();
System.out.println("Choose 1.for a-b, 2. for all even and 3. for odd numbers.");
int c = Lenijs.nextInt();
if (c == 1) {
do{
System.out.println(a);
a++;
}while(a<=b);
}
if(c == 2) {
if(a%2==0) {
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
else {
a++;
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
}
if(c == 3) {
if(a%2==0) {
a++;
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
else {
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
}
System.out.println("Do you wish to continue? (Yes/No)");
xdd=Lenijs.next();
}while(xdd.equals("Yes"));
}
}
How could I add a 4th option where the user can print out all 3, as of now you can individually select from 1-3 where u get for 1.just from a-b all numbers, 2.is a-b with only pairs and 3.is a-b only odd, but I wanted a 4th option where u could get them all together and is easy to read/overview. Is that possible to make or it won't look good/can't with my code?
It is generally a good practice to limit a method to doing just one thing. So the method that decides which action to perform should not be performing the action - it passes responsibility to the appropriate method(s). In this case, move each activity into a separate method and use a switch to invoke each as appropriate. The following illustrates the concept.
switch(c) {
case 1:
do1();
break;
case 2:
do2();
break;
case 3:
do3();
break;
case 4:
do1();
do2();
do3();
break;
default:
reportUnknownEntry(c);
}

Java using return value from method for if else statements

I made a method in java that prints a menu screen that looks like this:
MENU
c - Number of whitespace characters
f - Find text
r - Replace all !'s
q - Quit
Choose an option:
The method returns a char. How do I use the return value of the method in main to make if else statements?
printMenu method:
public static char printMenu(Scanner scnr) {
char menuOp;
//display the menu
System.out.println("\nMENU");
System.out.println( "c - Number of whitespace characters");
System.out.println("f - Find text");
System.out.println("r - Replace all !\'s");
System.out.println("q - Quit\n");
menuOp = ' ';
//loop until the user has entered a c, f, r or q
while (menuOp != 'c' && menuOp != 'f' &&
menuOp != 'r' &&
menuOp != 'q') {
System.out.println( "Choose an option:");
menuOp = scnr.nextLine().charAt(0);
}
//return the letter that the user entered
return menuOp;
} //end of the printMenu method
What I want to be able to do in main:
while (return value from printMenu method != 'q'){
printMenu(scnr);
if (return value from printMenu method == 'c'){ //do this
}
else if (return value from printMenu method == 'f'){ //do this
}
else if (return value from printMenu method == 'r'){ //do this
}
}
}
I'm still new and really appreciate the help, patience, and kindness. Thanks
Edit - I have to use the return value from printMenu() as a requirement for a project.
This seems like a good example for using a do-while loop:
Scanner scanner = new Scanner(System.in);
char c;
do
{
c = printMenu(scanner);
switch (c)
{
case 'c':
//do something
break;
case 'f':
//do something
break;
case 'r':
//do something
break;
}
} while(c != 'q');
Answered by sweeper:
menuChar = printMenu(scnr);

How to use instanceof in Java?

So I have an arrayList with rooms and im getting the user to put in the room they are looking for, im capturing this as a string and then trying to use instanceOf to match it up with the names of the java classes but cant do this due to comparing a string to a java class.
Also I am capturing there answer in a switch statement to make sure the classes are perfectly spelt and what not. just not sure how to reach in the arrayList and pull out the class they are looking for.
public static void serachRooms(ArrayList<Room> rooms) {
int option = 0;
String temp = "";
boolean flag = false;
do {
System.out.println("please Enter What room Type you would like:"
+ "\nNormal Room = 1"
+ "\nComputer Room = 2"
+ "\nBiology Lab = 3"
+ "\nBoard Room = 4"
+ "\nYou must choose one!");
option = input.nextInt();
if (option == 1 || option == 2 || option == 3 || option == 4) {
flag = true;
}
} while (!flag);
switch (option) {
case 1:
temp = "BiologyLab";
break;
case 2:
temp = "BoardRoom";
break;
case 3:
temp = "ComputerRoom";
break;
case 4:
temp = "Room";
break;
}
for (Room room : rooms) {
if (temp instanceof BiologyLab) {
}
}
}
instanceof is something pretty special that has to do with types and inheritance. Check out the Java documentation.
For your case, you want to compare the String temp to the String "BiologyLab". Just use
if ("BiologyLab".equals(temp)) {
...
}
and check out How To Compare Strings In Java for more information.

Validate User Input Using Java Chars and Strings

I have seen this asked 2x, but the correct response I need has not been addressed.
In this assessment,
you will design and code a Java console application that
validates the data
entry
of a course code (like IT4782)
and
report
back if the
course code is valid or
not
valid.
The
application
uses the Java char
and
String data types to implement
the validation.
You
can
use
either
the
Toolwire environment
or your
local
Java
development
environment
to complete this
assignment.
The requirements of
this application are
as follows:
The application is to read
a course code
entered
by the user
from the
keyboard.
The course code
is made
of 5 characters and should
follow
these
Rules:
First
character
is always
an
upper
case I
or a lower
case i
Second character
is always an upper
case
T or
a lower
case t
Third,
fourth,
fifth,
and sixth characters
are always digits (0-
9)
The application then validates the course code against
above the rules and prints a
message
If the
course code
is valid
or not.
If the course code is not
valid,
the application should print
a message
explaining why
the course
code is not
valid.
Output should look like this:
Here is my code, I cannot get the code to produce the pictured results. It outputs all the invalid messages.
package u4a1_validatecoursecode;
import java.util.Scanner;
public class U4A1_ValidateCourseCode {
public static void main(String[] args) {
// Larry Copy
Scanner s = new Scanner(System.in);
System.out.print("Enter a course code to validate (e.g. IT4782) : ");
String code = s.nextLine();
if (validateCode(code)) {
System.out.println("Course code: " + "" + code + "" + " is valid.");
} else {
System.out.println("Not valid code");
}
}
private static boolean validateCode(String code) {
if (code.length() != 6) {
return false;
} else {
//First character is always an upper case I or a lower case i
if (code.charAt(0) != 'I' && code.charAt(0) != 'i') {
return false;
}
System.out.println("integer is not an I or i");
// Second character is always an upper case T or a lower case t
if (code.charAt(1) != 'T' && code.charAt(1) != 't') {
return false;
}
System.out.println("integer is not a T or t");
// Third, fourth, fifth, and sixth characters are always digits (0-9)
if (!Character.isDigit(code.charAt(2))) {
return false;
}
System.out.println("integer 3 is not a number");
if (!Character.isDigit(code.charAt(3))) {
return false;
}
System.out.println("integer 4 is not a number");
if (!Character.isDigit(code.charAt(4))) {
return false;
}
System.out.println("integer 5 is not a number");
if (!Character.isDigit(code.charAt(5))) {
return false;
}
System.out.println("integer 6 is not a number");
return false;
}
}
}
When you return false; the code after is not executed so you'll never see why it returns
If you return only false the test will never pass, you need a variable to validate or not the code
If it goes in one if (not valid) you'll get the message, and the valid will be false
private static boolean validateCode(String code) {
if (code.length() != 6) {
return false;
} else {
boolean valid = true;
//First character is always an upper case I or a lower case i
if (code.charAt(0) != 'I' && code.charAt(0) != 'i') {
System.out.println("integer is not an I or i");
valid = false;
}
// Second character is always an upper case T or a lower case t
if (code.charAt(1) != 'T' && code.charAt(1) != 't') {
System.out.println("integer is not a T or t");
valid = false;
}
// Third, fourth, fifth, and sixth characters are always digits (0-9)
if (!Character.isDigit(code.charAt(2))) {
System.out.println("integer 3 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(3))) {
System.out.println("integer 4 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(4))) {
System.out.println("integer 5 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(5))) {
System.out.println("integer 6 is not a number");
valid = false;
}
return valid;
}
}
You are using too much line of code:
Here what I do:
private static boolean validateCode(String code,String validCode) {
boolean b=true;
if (code.length() != 6) {
return false;
}
for(int i=0;i<code.length();i++){
if(code.toLowerCase().charAt(i)!=validCode.toLowerCase().charAt(i) && i<2){
System.out.println("Character at "+i+" position is not an "+ validCode.charAt(i));
b= false;
}
if(Character.isDigit(code.charAt(i)) && i>2){
System.out.println("Character at "+i+" is not a digit");
b= false;
}
}
return b;
}

Categories