Make a loop with a-z input - java

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

Related

Can Java delimit input itself, without explicit delimiters?

My calculator, that I needed to make for my test task to apply for a Java course, is working great. But there's an issue I would like to resolve. If you type in, for example, "5+3" as opposed to "5 + 3", it doesn't work. Can my calculator be smart enough to delimit input without explicit delimiters (like spaces)?
In other words, how do I make my scanner split, for example, an input of 5+32 *2 into five tokens: 5, +, 32, *, and 2? If I don't have to overhaul my entire code, that would be even better!
import java.util.Scanner;
import java.io.IOException;
import java.text.DecimalFormat;
public class Introduction {
private static double firstNum;
private static double secondNum;
private static double result;
private static boolean dontKnow;
private static String firstNumS;
private static String secondNumS;
private static String operationS;
private static final DecimalFormat df = new DecimalFormat("#.##");
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
firstNumS = scanner.next();
operationS = scanner.next();
secondNumS = scanner.next();
if(firstNumS.compareTo(operationS) > 15){
switch(firstNumS){
case "I":
firstNum = 1;
break;
case "II":
firstNum = 2;
break;
case "III":
firstNum = 3;
break;
case "IV":
firstNum = 4;
break;
case "V":
firstNum = 5;
break;
case "VI":
firstNum = 6;
break;
case "VII":
firstNum = 7;
break;
case "VIII":
firstNum = 8;
break;
case "IX":
firstNum = 9;
break;
case "X":
firstNum = 10;
break;
default:
System.out.println("I don't know the first number!");
dontKnow = true; }}
else {
firstNum = Integer.decode(firstNumS);
if(firstNum > 10){
System.out.println("It appears, the first number is too big for me!");
dontKnow = true;
}
}
if(secondNumS.compareTo(operationS) > 15) {
switch(secondNumS){
case "I":
secondNum = 1;
break;
case "II":
secondNum = 2;
break;
case "III":
secondNum = 3;
break;
case "IV":
secondNum = 4;
break;
case "V":
secondNum = 5;
break;
case "VI":
secondNum = 6;
break;
case "VII":
secondNum = 7;
break;
case "VIII":
secondNum = 8;
break;
case "IX":
secondNum = 9;
break;
case "X":
secondNum = 10;
break;
default:
System.out.println("I don't know the second number!");
dontKnow = true; }}
else {
secondNum = Integer.decode(secondNumS);
if(secondNum > 10) {
System.out.println("It appears, the second number is too big for me!");
dontKnow = true; }}
if(operationS.equals("+")) {
result = firstNum + secondNum; }
else if(operationS.equals("-")) {
result = firstNum - secondNum; }
else if(operationS.equals("*")){
result = firstNum * secondNum; }
else if(operationS.equals("/")){
result = firstNum / secondNum; }
else {
System.out.println("I don't know such an operation!");
dontKnow = true; }
if(!(operationS.equals("/") && secondNum == 0)) {
if(!dontKnow) {
if(result / (int)result != 1) {
if(String.valueOf(result).equals(df.format(result))) {
System.out.println("It's " + result + "!"); }
else {
System.out.println("It's approximately " + df.format(result) + "!"); }}
else {
System.out.println("It's " + (int)result + "!"); }}}
else {
if(!dontKnow) {
System.out.println("Gosh! I tried to divide it by zero, as you requested, but my virtual head nearly exploded! I need to recover..."); }
else {
System.out.println("Besides, you can't even divide by zero, I'm so told!"); }}
}
}
Assuming you're using scanner, yes, it could. The scanner operates on the notion that a regexp serves as delimiter: Each match of the regex delimits, and whatever the regexp matches is tossed out (because nobody 'cares' about reading the spaces or the commas or whatever). The scanner then gives you stuff in between the delimiters.
Thus, for you to end up with scanner stream '5', '+', and '3', you want a delimiter that delimits on the space between '5' / '+' and '+' / '3', whilst matching 0 characters otherwise those would be thrown out.
You can do that, using regexp lookahead/lookbehind. You want a digit to the left and an operator to the right, or vice versa:
String test = "53 + 2*35- 8";
Scanner s = new Scanner(test);
s.useDelimiter("\\s+|(?:(?<=\\d)(?=[-+/*]))|(?:(?=\\d)(?<=[-+/*]))");
while (s.hasNext()) {
System.out.println("NEXT: '" + s.next() + "'");
}
To break that convoluted regex open:
A|B|C means: A or B or C. That's the 'outermost' part of this regexp, we're looking for one of 3 distinct things to split on.
\\s+ means: 1 or more whitespace characters. Thus, input "5 20" would be split into 5 and 20. The whitespace is consumed (i.e. tossed out and not part of your tokens).
OR, positive lookbehind ((?<=X) means: Match if, looking backwards, you would see X), and X is \\d here - a digit. We then also have a positive lookahead: (?=X) means: Check for X being here, but don't consume it (or it would be thrown out, remember, the regex describes the delimiter, and the delimiter is thrown out). We look ahead for one of the symbols.
OR, that, but flipped about (first an operator, then a digit).
NB: If you want to avoid the complexity of a regexp, you could just loop through each character, but you'd be building a little state machine, and have to take care of consecutive, non-space separated digits: You need to combine those (10 + 20 is not 1, 0, +, 2, 0 - it's 10 + 20).
NB2: If you also want to support ( and ) you can edit the regex appropriately (They are, essentially, 'operators' and go in the list of operators), however, at some point you're essentially descriving a grammar for a formal language and should start looking into a parser generator. But that's all vastly more complicated than any of this.

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'

Java character option pane

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;

check is String vowel or consonant using java?

How do I check whether a String begins with a vowel or a consonant sound? For instance, University begins with a consonant sound; Hour begins with a vowel sound.
public static void main(String args[])
{
char ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a word : ");
ch = scan.next().charAt(0);
if(ch=='a' || ch=='A' || ch=='e' || ch=='E' ||
ch=='i' || ch=='I' || ch=='o' || ch=='O' ||
ch=='u' || ch=='U')
{
System.out.print("This is a Vowel");
}
else
{
System.out.print("This is not a Vowel");
}
}
You cannot do this reasonably simply by examining the first letter. Rather, you need to refer to an on-line dictionary and use the first phoneme of the pronunciation. You've already coded the simple implementation: check the first letter. However, as your counterexamples show, this is not enough.
If this is a homework assignment, please contact your instructor for access to the pronunciation file.
public static int vovelsCount(String str) {
return str.replaceAll("[^aeiou]","").length();
}
import java.util.Scanner;
/**
* Java Program to count vowels in a String. It accept a String
from command promptand count how many vowels it contains. To revise,
5 letters a, e, i, o and u are known as
vowels in English.
*/
public class VowelCounter {
public static void main(String args[]) {
System.out.println("Please enter some text");
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
char[] letters = input.toCharArray();
int count = 0;
for (char c : letters) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
default:
// no count increment
}
}
System.out.println("Number of vowels in String [" + input + "] is : " + count);
}
}

Java Debugging, syntax issues [duplicate]

This question already has answers here:
Why can't I do assignment outside a method?
(7 answers)
Closed 6 years ago.
I have a couple debug issues I cant figure out. I commented them out in the code below, if someone could please correct it AND explain why the errors happened, I would really appreciate it. I'm new to java, and this is one of the first few projects I'm working on
public class handleexceptions2 {
int sideA = -1;
int sideB = -1;
Scanner input = new Scanner(System.in){
do //Syntax Error on Token "do", delete this token
{
System.out.println("Enter your choice ( a/b/c/q ) : ");
char ch = in.nextChar();
switch(ch)
{
case 'a': sideA = in.nextDouble();
if(sideA<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'b': sideB = in.nextDouble();
if(sideB<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'c': if(sideA<0 || sideB<0)
System.out.println("Other two sides not yet given! please provide a and b first. ");
else
System.out.print("Side C(the hypotenuse) is: "+ Math.sqrt((sideA*sideA) + (sideB*sideB)));
break;
case 'q': break;
default : System.out.println(" Enter a valid choice! ");
}
while(ch!='q');
} //Multiple markers at this line
Syntax Error, insert "}" to complete class body
Syntax Error, insert ";" to complete FieldDecleration
//
// The Scanner class is found in java.util, so it needs to be imported.
import java.util.*;
// As per convention, classes should always start with an uppercase letter, and you should
// capitalize each word.
public class HandleExceptions2 {
// The main method will get called when you run the class.
public static void main(String[] args) {
// These need to be doubles, and not integers since you are reading doubles from the input.
double sideA = -1;
double sideB = -1;
// You had "{" at the end of this line, which would allow you to create an anonymous class
// extending Scanner, which was certainly not your intention.
Scanner input = new Scanner(System.in);
// 'ch' needs to be defined outside the loop since you are using it in your 'do while' loop
// condition.
char ch;
do {
System.out.println("Enter your choice ( a/b/c/q ) : ");
// Your scanner is called 'input' not 'in'. Also, nextChar() is not a method in the Scanner
// class, so perhaps you want to read the entire line and grab the first character?
ch = input.nextLine().charAt(0);
switch (ch) {
case 'a':
sideA = input.nextDouble();
// We want to finish reading this line (so that the next time we call nextLine() we don't
// just get an end-of-line character).
input.nextLine();
if (sideA < 0)
System.out.println("Error! Please enter a valid number!");
break;
case 'b':
sideB = input.nextDouble();
input.nextLine();
if (sideB < 0)
System.out.println("Error! Please enter a valid number!");
break;
case 'c':
if (sideA < 0 || sideB < 0)
System.out.println("Other two sides not yet given! please provide a and b first. ");
else
// You probably want to finish writing the line here (System.out.print() doesn't add a
// line break).
System.out.println("Side C(the hypotenuse) is: " + Math.sqrt((sideA*sideA) + (sideB*sideB)));
break;
case 'q': break;
default : System.out.println(" Enter a valid choice! ");
}
// The while loop condition needs to be placed right after the matching bracket after 'do'
} while (ch != 'q');
}
}
Put your code in a function for instance:
public class handleexceptions2 {
public static void main(String... args) {
...your code here...
}
}

Categories

Resources