Java character option pane - java

I'm doing a basic calculator, I got confuse how to make this do a do while loop for it to execute again. Any suggestions? I'm just starting to learn Java so I'm a beginner. I only have trouble at the "Do you want to try again" Part. Is there a character parse like Integer.parseInt for character data types? or string data type? Thank you
public static void main(String[] args) {
Calc2 op = new Calc2();
Scanner scan = new Scanner(System.in);
char ans = 0;
do {
String c = JOptionPane.showInputDialog("Calculator\n" + "1.Addition\n" + "2.Subtraction\n" + "3.Multiplication\n" + "4.Division\n");
int n1 = Integer.parseInt(c);
switch (n1) {
case 1:
op.add();
break;
case 2:
op.diff();
break;
case 3:
op.prod();
break;
case 4:
op.quo();
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Input", "Calculator", JOptionPane.PLAIN_MESSAGE);
break;
}
String s1 = JOptionPane.showInputDialog("Try again? [Y/N]");
int a = Integer.parseInt(s1);
} while (ans == 'y' || ans == 'Y');
}

You don't need to parse a character and should remove:
int a = Integer.parseInt(s1);
and change the following line:
} while (ans == 'y' || ans == 'Y');
to:
} while (JOptionPane.showInputDialog("Try again? [Y/N]").equalsIgnoreCase("y"));
and remove the unnecessary lines:
Scanner scan = new Scanner(System.in);
char ans = 0;

Related

Make a loop with a-z input

I am a complete noob to Java, but I wish to make a program that takes an input from user, [A/a] - [C/c], [D/d] - [F/f], and so on, and then returns a value ([A/a-C/c = 1], [D/d-F/f = 2]....
If the input is not A-Z or a-z, returns a "Invalid input". (I think I can figure this one out myself).
I suppose I could make a "ToUpperCase" statement on the input, but I am not entirely sure how to do so.
I would prefer not to use any special databases.
Here is my code so far:
import java.util.Scanner;
public class TelefonTastatur {
public static void main(String[] args) {
String korrTall = "Korresponderer til tallet "; //Strings are in Norwegian, but I don't need help with those :-)
System.out.println("Dette programmet konverterer bokstav-input til korresponderende tall på et telefontastatur.");
System.out.println("Oppgi en bokstav (A-Z: "); //Asks user for A-Z input.
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0); //Perhaps toUpperCase to lower number of switch cases?
switch (c) {
case ('A'-'C'): //Not sure how to make A-C and/or a-c. I could make an individual case for all inputs, but that would make a lot of code.
case ('a'-'c'):
System.out.print(korrTall + "2.");
break;
case (D/d - F/f):
case ():
System.out.print(korrTall + "3.");
break;
case (G/g - I/i):
case ():
System.out.print(korrTall + "4.");
break;
case (J/j - L/l):
case ():
System.out.print(korrTall + "5.");
break;
case (M/m - O/o):
case ():
System.out.print(korrTall + "6.");
break;
case (P/p - S/s):
case ():
System.out.print(korrTall + "7.");
break;
case (T/t - V/v):
case ():
System.out.print(korrTall + "8.");
break;
case (W/w - Z/z):
case ():
System.out.print(korrTall + "9.");
break;
case 'F':
case 'f':
System.out.print(korrTall + "0.");
break;
default:
System.out.println("Det du har tastet inn tilsvarer ikke noe tall på et telefontastatur.");
break;
}
}
}
If you want to read a single letter from the user you can use the readInput()provided in the code snippet.
Then, for example in your main(), you could ask for the user to input 2 letters and then you will provide him the result.
public static void main(String[] args) {
try{
char inputOne = readInput();
char inputTwo = readInput();
handle(inputOne,inputTwo);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
static char readInput(){
System.out.println("Insert a character");
String input = Console.readLine();
if (input.length==0) {
char c = input.charAt(0);
if (Character.isLetter(c)) {
return c;
}
}
throw new Exception("Invalid input!");
}
static void handle(char a, char b){
// your logic to handle the input of the user
}
Your question is not clear at all but i try to help you. Next time post what u tried.
This simple code will help you, this can be improved so let's do this :D
Scanner scanner = new Scanner(System.in);
System.out.println("Insert first char");
String firstChar = scanner.next().toUpperCase();
if (firstChar.length() != 1 || (firstChar.toCharArray()[0] < 65 || firstChar.toCharArray()[0] > 90)) {
System.out.println("Please, insert one single character [a-z/A-Z]");
return;
}
System.out.println("Insert second char");
String secondChar = scanner.next().toUpperCase();
if (secondChar.length() != 1 || (secondChar.toCharArray()[0] < 65 || firstChar.toCharArray()[0] > 90)) {
System.out.println("Please, insert one single character");
return;
}
System.out.println(firstChar + " - " + secondChar + " = " + Math.abs(firstChar.toCharArray()[0] - secondChar.toCharArray()[0]));
Note that You can create methods to do repetitive action. In this simple example you can create a method that check if what you just read from keyboard is a single character.
One other improve you can do is handle when user insert something wrong.
Let's try to code :D
Bye
You're going to have to use the Scanner class to accomplish user input.
import java.util.Scanner;
Then create a variable that takes in the keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a letter: ");
String text = keyboard.nextLine();
Create a method that returns a number given a character.
a-z is equal to 97-122 in Java, and A-Z is equal to 65-90.
public int toNum(String text) {
//Ensure that the text is only 1 character long.
if(text.length() > 1) return -1;
//Convert the one-character String to type char.
char letter = text.charAt(0);
//Convert char to its equivalent number value.
int rawNum = letter;
int newNum;
//Convert the number to a value 0-25.
if(rawNum >= 'a' && rawNum <= 'z') {
newNum = rawNum - 'a';
} else if(rawNum >= 'A' && rawNum <= 'Z') {
newNum = rawNum - 'A';
} else {
//None of the characters were letters A-Z.
System.out.println("Invalid input");
return -1;
}
//If {a,b,c} are 1 and {d,e,f} are 2, then {0,1,2} -> 1 and {3,4,5} -> 2
//Take the floor of the new number divided by 3.
int toReturn = Math.floor(newNum / 3.0) + 1;
return toReturn;
}
Now just call your method with the user input.
toNum(text);
You can print the returned value of the user input as well.
System.out.println(toNum(text));

Scanner skipping nextLine(); after do while loop

as you can probably see I am a newbie in java. Below is a simple calculator program which asks for the user to input a symbol such as + or -. The user then inputs 2 numbers and depending on the operator symbol chosen a method will be called. A do while loop allows the user to repeat the process. The problem is that after the program loops, the following line: "String symb = inp.nextLine();" is skipped. I have already tried searching for a solution however I only found a fix if the nextLine is called after nextInt. Thank you in advance for your patience.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inp = new Scanner(System.in);
Methods operation = new Methods();
boolean loop = false;
do {
System.out.println("Enter an operator symbol - +, -, * or /");
String symb = inp.nextLine(); //this is the line which is skipped
System.out.println("Enter a number");
int num1 = inp.nextInt();
inp.nextLine();
System.out.println("Enter a second number");
int num2 = inp.nextInt();
inp.nextLine();
switch(symb) {
case "+" :
operation.setA(num1);
operation.setB(num2);
int totalAddition = operation.addNums(num1,num2);
System.out.println("The result is - " + totalAddition);
break;
case "-" :
operation.setA(num1);
operation.setB(num2);
int totalSubtract = operation.subtractNums(num1,num2);
System.out.println("The result is - " + totalSubtract);
break;
case "*" :
operation.setA(num1);
operation.setB(num2);
int totalMult = operation.multNums(num1,num2);
System.out.println("The result is - " + totalMult);
break;
case "/" :
operation.setA(num1);
operation.setB(num2);
int totalDiv = operation.divNums(num1,num2);
System.out.println("The result is - " + totalDiv);
break;
}
System.out.println("Would you like to exit? Y/N");
char ans = inp.next().charAt(0);
if(ans == 'Y' || ans == 'y') {
loop = true;
inp.close();
System.exit(0);
}
else {
loop = false;
}
}
while(loop == false);
}
}

Variable cannot be resolved, error in Eclipse but not BlueJ

Yes there are plenty of duplicates to this question, I know.
The following code has no problems compiling in BlueJ, however, when ran in Eclipse I get the error on the following line:
while (selection != 'Q' && selection != 'q');
The error is: selection cannot be resolved to a variable.
Why do I experience this error in Eclipse and not BlueJ?
public class menuMain {
public menuMain(String args) {
System.out.println("Welcome to the Project");
Scanner in = new Scanner(System.in);
do {
showMenu();
String menu = in.nextLine(); // read a line of input
char selection;
if (menu.length() > 0) {
selection = menu.toLowerCase().charAt(0); // extract the first char of the line read
}
else {
System.out.println("invalid input:\t"+selection);
System.out.println("Press enter to continue...");
Scanner itScan = new Scanner(System.in);
String nextIt = itScan.nextLine();
}
switch (selection)
{
case 'a':
changeTime time = new changeTime ();
break;
case 'b':
watchTime timeStop = new watchTime();
break;
case 'q':
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
}
while (selection != 'Q' && selection != 'q');
System.exit(0);
}
}
As YCF_L mentioned char selection: is out of scope. When working in Eclipse I usually declare it before do while statement. Do not think to much about it ;-)

Going out from a switch inside a do while, but without a boolean, it's possible? Java

So the code is about giving a limit of inputs in a do while.
In this case you have 3 oportunities to continue. After that the do while stops, also you have the oportunitie to stop just presing any key plus enter, but also when you start, do you have the oportunitie (here enters the switch) to exit the program.
The problem or where I get stuck is here.
That maybe it's possible without a boolean, or maybe changing or adding something that I don't yet know. Sorry I try to find an answer but all I saw it's about going out a while loop whith boolean or so. Not like this.
Scanner kb = new Scanner(System.in);
// c = continue
char c;
// attempt to limit the input to 3 times
int attempt = 3;
// option = op
int op = 0;
do {
do{
System.out.println("Choose continue[0] or go out[1].");
while (!kb.hasNextInt()) {
kb.nextLine();
System.out.println("It's not a number.");
}
op = kb.nextInt();
} while ( op <= -1 || op >= 2 );
switch (op) {
case 0:
System.out.println("Continue!");
break;
case 1: //here I tried; attempt = -1
break; //is where I think it needs to be something
default:
break;
}
System.out.println("Do you wanna try again,"+attempt+" less?[c]+enter\n"
+ "Any other key + enter to exit.");
c = kb.next(".").toUpperCase().charAt(0);
attempt--;
} while ( attempt > 0 && ( c == 'C' ) );
//here also to put !( op == 0 )
kb.close();
I think you can do this pretty easily without a case switch by using a method:
static Scanner kb = new Scanner(System.in);
public static void main(String args[]){
if(getContinueOption(3)){
//do what you want to do
}
}
private static boolean getContinueOption(int attempts) {
System.out.println("Would you like to continue? Y[1] : N[0]");
while(attempts > 0){
int input = kb.nextInt();
if(input == 1){
return true;
}
attempts--;
System.out.println( (attempts == 0)? "Ok :(" : "Are you sure?");
}
return false;
}
You only need to ask for continuation if user chooses 0.
Scanner kb = new Scanner(System.in);
// c = continue
char c = 'a';
// attempt to limit the input to 3 times
int attempt = 3;
// option = op
int op = 0;
do {
do{
System.out.println("Choose continue[0] or go out[1].");
while (!kb.hasNextInt()) {
kb.nextLine();
System.out.println("It's not a number.");
}
op = kb.nextInt();
} while ( op <= -1 || op >= 2 );
switch (op) {
case 0:
System.out.println("Continue!");
System.out.println("Do you wanna try again,"+attempt+" less?[c]+enter\n"
+ "Any other key + enter to exit.");
c = kb.next(".").toUpperCase().charAt(0);
attempt--;
break;
case 1:
attempt = -1;
break;
default:
break;
}
} while ( attempt > 0 && ( c == 'C' ) );
kb.close();
This question is a little hard to understand, but I think what you want is...
Scanner kb = new Scanner(System.in);
// c = continue
char c;
// attempt to limit the input to 3 times
int attempt = 3;
// option = op
int op = 0;
the_loop:
do {
do{
System.out.println("Choose continue[0] or go out[1].");
while (!kb.hasNextInt()) {
kb.nextLine();
System.out.println("It's not a number.");
}
op = kb.nextInt();
} while ( op <= -1 || op >= 2 );
switch (op) {
case 0:
System.out.println("Continue!");
break;
case 1: //here I tried; attempt = -1
break the_loop; //is where I think it needs to be something
default:
break;
}
System.out.println("Do you wanna try again,"+attempt+" less?[c]+enter\n"
+ "Any other key + enter to exit.");
c = kb.next(".").toUpperCase().charAt(0);
attempt--;
} while ( attempt > 0 && ( c == 'C' ) );
//here also to put !( op == 0 )
kb.close();
Note the_loop and break the_loop;
It's actually simpler than that and avoids the use of if statements, although I am not sure why you would do it this way in real life, it's a good exercise to go over concepts.
Let's look at the implementation first:
import java.util.*;
import java.lang.*;
class SillyEnforcer {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
char c = 'C';
int attempt = 3;
int op = 0;
while(attempt > 0 && c == 'C') { // attempt loop
do {
System.out.println("Enter 0 to continue, 1 to exit");
while (!kb.hasNextInt()) {
kb.nextLine();
System.out.println("Not a number, try again.");
}
op = kb.nextInt();
switch(op) {
case 0:
continue;
case 1:
op = -1;
break;
default:
System.out.println("Number can only be 0 or 1.");
op = 0; // positional trickery
continue;
}
} while(op != -1);
System.out.println("Do you wanna try again, ("+ attempt + " attempt" +
((attempt > 1) ? "s" : "") + " left) ? C<ENTER> to continue\n"
+ "Any other key<ENTER> to exit");
c = kb.next(".").toUpperCase().charAt(0);
attempt = attempt - ((c == 'C') ? 1 : 0);
}
}
}
Inner magic
Notice that by using continue for case 0 and reassigning op=-1 for case 1 we can manage the messages correctly and by assigning op=0 in default: we take care of the edge case where a clever person enters -1 as the integer above.
And notice that we make the while statement exit on op == -1. This makes the flag which exits while separate from the input which gives you the magic you need to cover all cases. -1 will never happen by input, (we fix that in default) and 0 is the only thing that sets op to -1. All other cases continue the inner while loop.
'C' for continue magic
We only want to decrease attempt if someone actually wants to continue otherwise we exit anyways, it does not matter here but you can extend this logic to change the question to "do you want to exit [Y/n]" and loop if answer is not a 'Y' or an 'n' while decreasing attempt only on a valid answer of 'Y'

Error handling with strings java

I'm trying to add error handling to my java program if anything but the options and String/char are entered. I mainly need it for if a String is entered. I've tried to do the while(true) but I don't really understand that. I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. So I just need help adding error handling to my program. Thanks!
here's my code
import java.util.*;
public class HeroesVersusMonsters
{
private static Hero hero;
private static Monster monster;
private static Random rand = new Random();
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do
{
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
int choice = kb.nextInt();
kb.nextLine();
while (choice < 1 && choice > 4 )
{
System.out.println("\n" + choice + " is not an option. Please try again.");
System.out.print("Choice --> ");
choice = kb.nextInt();
kb.nextLine();
System.out.println();
}
switch (choice)
{
case 1:
hero = new Warrior();
break;
case 2:
hero = new Sorceress();
break;
case 3:
hero = new Thief();
break;
case 4:
hero = new Snake();
break;
}
switch (rand.nextInt(3))
{
case 0:
monster = new Ogre("Shrek the Ogre");
break;
case 1:
monster = new Skeleton("Bones the Skeleton");
break;
case 2:
monster = new Gremlin("Dobby the Gremlin");
break;
}
System.out.println();
System.out.println(hero.name + ", you will be fighting against " + monster.getName() + "!!!");
System.out.println();
while (hero.getHits() > 0 && monster.getHits() > 0)
{
hero.attack(monster);
monster.attack(hero);
}
System.out.print("Would you like to play again? (yes / no) ");
String play = kb.nextLine().toLowerCase();
play = play.trim();
if (play.equals("no"))
break;
else
System.out.println();
}
while (true);
}
}
Please look closly to your condition of inner while loop.
while (choice < 1 && choice > 4 )
Means loop will work until choice<1 and choice>4 remains true.
Is it exactly what you want?
I think No because what if input is 5 it is true for >4 but false for <1 what you want is you need to loop things until user enters correct input.
Am I right?
So what you need to do is just change condition like this
while(choice<1 || choice>4)
As Jared stated.
One more thing I want to suggest you don't you think you should break; external loop while user enters wrong input.(No problem)
You can do one this also.
ArrayList<Integer> ar=new ArrayList<Integer>(4);
ar.add(1);
ar.add(2);
ar.add(3);
ar.add(4);
while(true)
{
if(ar.contains(choice))
{
//Go On
}
else
{
//Print old stuff
}
}
Here is what your main method should look like:
public static void main(String ...args){
final Scanner scanner = new Scanner(System.in);
while(true){
final Hero hero = promptHero(scanner);
final Monster monster = getRandomMonster();
fight(hero, monster);
if(!playAgain(scanner))
break;
}
}
Now write the static methods promptHero, getRandomMonster, fight, and playAgain (which should return true if you want to play again).
Here is what your promptHero method should look like (to properly handle bad input):
private static Hero promptHero(final Scanner scanner){
while(true){
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
try{
final int choice = scanner.nextInt();
if(choice < 1 || choice > 4)
System.out.println("\n" + choice +
" is not an option. Please try again.");
else
return getHero(choice); //return the hero
} catch(InputMismatchException ime){
final String line = scanner.nextLine();// need to advance token
System.out.println("\n" + line +
" is not an option. Please try again.");
}
}
}
private static Hero getHero(final int choice){
switch (choice){
case 1:
return new Warrior();
case 2:
return new Sorceress();
case 3:
return new Thief();
case 4:
return new Snake();
}
return null;
}
You should check out the Java regex:
if(choice.toString().matches("[0-9]+"))
{
//continue
}
else
{
//error message
}

Categories

Resources