// I am stuck trying to get my program to only accept a single character from the scanner. Right now the program will accept any amount of characters as long as the first letter is one of the listed letters. I would like to rewrite this code with out the charAt(0) if possible or to add a if statement. if(sea.length > 1){} something like that. I hope I explained the issue well enough to understand. Any help is appreciated, and thank you for your time.
public static char promptForChoice(Scanner in) {
System.out.println("High, Low or Seven(H/L/S");
char sel = in.next().charAt(0);
sel = Character.toUpperCase(sel);
int i = 1;
while (i != 0) {
System.out.println("High, Low or Seven(H/L/S");
if (sel == 'H' || sel == 'L' || sel == 'S') {
i = 0;
} else {
System.out.println("You must enter only H, L or S.");
i = 1;
}
}
return sel;
}
Is there a char.length command?
No, there is no such command. You need to get the input using Scanner::nextLine() and check the length of the input String.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
Scanner in = new Scanner(System.in);
System.out.println(promptForChoice(in));
}
public static char promptForChoice(Scanner in) {
char sel = 0;
String input;
boolean valid;
do {
valid = true;
System.out.print("Enter H/L/S [High/Low/Seven]: ");
try {
input = in.nextLine();
sel = input.toUpperCase().charAt(0);
if (input.length() == 1 && (sel == 'H' || sel == 'L' || sel == 'S')) {
return sel;
} else {
throw new IllegalArgumentException("You must enter only H, L or S.");
}
} catch (IllegalArgumentException e) {
valid = false;
System.out.println(e.getMessage());
}
} while (!valid);
return sel;
}
}
A sample run:
Enter H/L/S [High/Low/Seven]: hello
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: High
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: M
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: H
H
Feel free to comment in case of any doubt/issue.
You could get the input from the scanner and put it into a string, then u can do string.length and check it!
the Character length is always 1, I suppose you could achieve what you need with
public static char promptForChoice(Scanner in) {
if(in.next() == "H" || in.next() == "L" || in.next() == "S") {
System.out.println("High, Low or Seven(H/L/S");
return (char) in.next();
}
else {
System.out.println("You must enter only H, L or S.");
// you must always have a return value, in this case
//e.g. the automatically initialized char value
return '\0';
}
}
with your code you could do something like
public static char promptForChoice(Scanner in) {
System.out.println("High, Low or Seven(H/L/S");
char sel = in.next().charAt(0);
if(in.next().length == 1) {
sel = Character.toUpperCase(sel);
int i = 1;
while (i != 0) {
System.out.println("High, Low or Seven(H/L/S");
if (sel == 'H' || sel == 'L' || sel == 'S') {
i = 0;
} else {
System.out.println("You must enter only H, L or S.");
i = 1;
}
}
}
else System.out.println("You must enter only one single character");
return sel;
}
Related
I created a program that convert text to ASCII value and now when i press Y to try again and input a new string there will be a error that string is out of range etc.
I am new in this field, I will appreciate your help.
And here is the Error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 17,length 17
at java.base/java.lang.String.checkIndex(String.java:3278)
at java.base/java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:307)
at java.base/java.lang.StringBuffer.charAt(StringBuffer.java:242)
at com.company.Main.main(Main.java:26)
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
boolean Flag; // The Boolean variable for the do while lopp
int n,l,j=0,m,i,ch;
char t;
StringBuffer data = new StringBuffer();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter any string and it will convert into numbers:- ");
data.append(input.nextLine());
l = data.length();
m = l;
System.out.println(l);
for (i = 0; i < m; i++) {
t = data.charAt(j);
n = (int) t;
System.out.print(n);
System.out.print(",");
j++;
}
data.delete(0, m-1);
System.out.println("\nDo you want to try again? Y/N");
ch = input.nextInt();
//Those are the condition for that the program should be run again or not
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
}
while(Flag=true);
System.out.println("Thanks, Come Again");
}
}
while(Flag=true);
this doesn't check whether the value of Flag is true, it sets it to true, and thus automatically returns true.
What you want is:
while(Flag==true);
or,
while(Flag);
for short.
You may also want to read up about naming conventions.
As for your Exception:
Y is not an int, change your
ch = input.nextInt();
to
ch = input.nextLine().charAt(0);
this will solve the initial problem, but still might lead to false results with unexpected input (or lack there of)
int n,l,j=0,m,i,ch;
This declaration is invalid. If all of these values are supposed to be
0, the declaration should look like:
int n, l, j, m, i, ch = 0
Also your logic in the nextInput section is incorrect.
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
Instead of the AND ( && ) this should be an OR ( || ). If it's 'Y' OR it's 'y'. It will likely never be both Y and y. This should be fixed as follows:
if (ch == 'Y' || ch == 'y') {
Flag = true;
} else if (ch == 'N' || ch == 'n') {
Flag = false;
}
Also, as mentioned by #Stultuske, you'll want to change your while condition to:
while (Flag == true)
One thing that's niggling at me here is that ch is an integer, but you're asking it if that value is 'Y, y, N, n' those are characters and not integers. I'm guessing that's why you got the 'Input_Mismatch_Exception'. Hope this helps.
Edit: Formatting
i've been trying to impelement rock,paper,scissor game in java.
when i try to use getinput method : the first try returns right output 1 , 2 or 3(rock,paper,scissor declared static final in gamelogic class ..)
but when i enter incorrect input then correct input it always returns 0 !
public int getInput(){
System.out.println("Select ROCK , PAPER or SCISSOR");
String choice = scanner.nextLine();
choice = choice.toUpperCase();
char c = choice.charAt(0);
if(c == 'R'){
return gameLogic.rock;
}else if(c == 'P'){
return gameLogic.paper;
}else if(c == 'C'){
return gameLogic.scissor;
}
getInput();
return 0;
}
try this
public static int getInput(){
int result = 0;
System.out.println("Select ROCK , PAPER or SCISSOR");
Scanner scanner = new Scanner(System.in);
String choice = scanner.nextLine();
choice = choice.toUpperCase();
char c = choice.charAt(0);
if(c == 'R'){
result = 1;
}else if(c == 'P'){
result = 2;
}else if(c == 'C'){
result = 3;
} else {
return getInput();
}
return result;
}
I am trying to get my loop to end when the user inputs the character N or n but when I run my program it will not end properly. It seems like the char for answer isn't being read by the loop itself so can someone please help me?
import java.util.Scanner;
public class Project4_Baker
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
char answer;
System.out.println("=============");
System.out.println("Prime or Not?");
System.out.println("=============");
do
{
System.out.print("Enter a whole number ==>");
int n = s.nextInt();
System.out.println();
if(isPrime(n))
{
System.out.println(n + " is a prime number.");
}
else
{
System.out.println(n + " is a composite number.");
}
System.out.println();
System.out.print("Do another (Y/N)==>");
answer = s.next().charAt(0);
}while(answer != 'N'|| answer != 'n');
}
public static boolean isPrime(int n)
{
if(n <= 1)
{
return false;
}
for (int i = 2; i < Math.sqrt(n); i++)
{
if (n%i==0)
{
return false;
}
}
return true;
}
}
my code will not end when it is supposed to
It should be while(answer != 'N' && answer != 'n');. With while(answer != 'N' || answer != 'n');, if somebody inputs N then it will continue because answer is equal to N but it is not equal to n.
try
while(answer != 'N' && answer != 'n');
You want the case where the character is NOT EQUAL to 'N' AND is also NOT EQUAL to 'n'
The problem resides in the loop condition.
while(answer != 'N' || answer != 'n')
The condition above will always be true.
Use this instead:
while(answer == 'Y' || answer == 'y')
You try to compare String with Char in your while lopp statement.
Convert your char to int and use unicode table to look up charcode, ex. n would be 110
Before your loop:
int a = 0;
Whithin your loop:
a = (int)answer;
...(while a != 110 || ...)
Wondering how to exit if total phrase is guessed and why my vowels, spaces and consonants are not counting? Most of progam runs great just cant figure out how to exit without saying "n" to question. I am returning values for counters, don't understand?
import java.util.Scanner;
public class Prog09
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initializes all string variables
String sPhrase;
String answer;
// Initializes all int variables
int vowels = 0;
int consonants = 0;
int spaces = 0;
// Initializes all char variables
char cGuess = 0;
char vGuess = 0;
boolean valid = false;
// Asks user to enter if they want to play
System.out.print("Do you want to play a game? [y/n] ");
answer = stdIn.nextLine();
// Asks user to enter the phrase
System.out.print("Please enter the phrase to guess at : ");
sPhrase = stdIn.nextLine();
// Checks if user wants to play
while (answer.equalsIgnoreCase("y"))
{
char[] phrase = new char[sPhrase.length()];
char[] tmpArr = new char[sPhrase.length()];
for(int i = 0; i < sPhrase.length();i++)
{
tmpArr[i] = sPhrase.charAt(i);
phrase[i] = sPhrase.charAt(i);
}
// Runs methods and main body of program
initTemplateArray(sPhrase, tmpArr, spaces);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
while (answer.equalsIgnoreCase("y"))
{
//getConsonant(stdIn, cGuess);
cGuess = getConsonant(stdIn, cGuess);
vGuess = getVowel(stdIn, vGuess);
isVowel(vGuess, valid);
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, consonants, vowels);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
stdIn.nextLine();
System.out.print("Do you want to try again? [y/n]: ");
answer = stdIn.next();
vGuess = 0;
cGuess = 0;
}
}
// Prints results
System.out.println("The common phrase contained: Spaces: " + spaces + " Consonants: " + consonants + " Vowels: " + vowels);
stdIn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for program
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces)
{
for (int i = 0; i < sPhrase.length(); i++)
{
if (sPhrase.charAt(i) == ' ')
{
spaces++;
tmpArr[i] = ' ';
}
if (!(sPhrase.charAt(i) == ' '))
{
tmpArr[i] = '?';
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr)
{
for (int i = 0; i < tmpArr.length; i++)
{
System.out.print(tmpArr[i]);
}
System.out.println();
}
public static boolean isVowel(char c, boolean valid)
{
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
return valid = true;
}
else
{
return valid = false;
}
}
public static char getConsonant(Scanner stdIn, char cGuess)
{
while(cGuess == 'a' || cGuess == 'e' || cGuess == 'i' || cGuess == 'o' || cGuess == 'u'|| cGuess == 0)
{
System.out.print("Enter a lowercase consonant guess : ");
String myGuess = stdIn.next();
cGuess = myGuess.charAt(0);
}
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess)
{
while(!(vGuess == 'a' || vGuess == 'e' || vGuess == 'i' || vGuess == 'o' || vGuess == 'u'))
{
System.out.print("Enter a lowercase vowel guess : ");
String newGuess = stdIn.next();
vGuess = newGuess.charAt(0);
}
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int consonants, int vowels)
{
vowels = 0;
consonants = 0;
for (int i = 0; i < tmpArr.length; i++)
{
if (cGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
consonants++;
}
if (vGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
vowels++;
}
}
return consonants & vowels;
}
public static void printHeader()
{
System.out.println("");
System.out.println(" Common Phrase");
System.out.println("---------------");
}
}
Java passes Ints by value instead of by reference, this means that updateTemplateArray doesn't modify the values of main's vowels, consonants or spaces. To fix this you could:
Make these variables global by definining them outside the scope of the main method. You would have to change the name of the parameters in the updateTemplateArray method to prevent shadowing.
Break updateTemplateArray into separate functions to count each of the vowels, consonants or spaces, and have them return the count of each. You would then call something like: vowels = countVowels(sPhrase); to populate the variables.
With the current setup, it will exit whenever answer stops being equal to 'y' Changing the value of answer at any time will exit the loop.
I have a method that should scan for one of 3 letters in caps or lowercase and return the lower case version of the letter. If an improper letter is entered the user is warned and reasked for a letter. I have two issues, 1: as soon as the method is run I get the outputted line with the error message telling the user invalid entry without waiting for an entry! (so the second the method is run I see High, low or sevens (H/L/S):Invalid entry. Please try again using H/L/S! before entering anything then the method is recalled again and all works fine form there except for my next issue) 2: the entry that is gotten from the scanner never passes any of my if statements even though it should.
my code:
private static char getHighLow(Scanner inScanner) {
System.out.print("High, low or sevens (H/L/S):");
String entered = inScanner.nextLine();
System.out.print(entered);
if(entered.equals("H") || entered.equals("h")){
return 'h';
}
else if (entered.equals("L") || entered.equals("l")){
return 'l';
}
else if(entered.equals("S") || entered.equals("s")){
return 's';
}
char result = 0;
while(result != 'l' || result != 'h' || result != 's'){
System.out.println("Invalid entry. Please try again using H/L/S!");
result=getHighLow(inScanner);
}
return result;
}
Instead of using while(), you can use 'else' like this-
private static char getHighLow(Scanner inScanner) {
System.out.print("High, low or sevens (H/L/S):");
String entered = inScanner.nextLine();
System.out.print(entered);
if(entered.equals("H") || entered.equals("h")){
return 'h';
}
else if (entered.equals("L") || entered.equals("l")){
return 'l';
}
else if(entered.equals("S") || entered.equals("s")){
return 's';
}
else {
System.out.println("Invalid entry. Please try again using H/L/S!");
return getHighLow(inScanner);
}
}
You can simply use equalsIgnoreCase and trim the entered string. And add a while loop util your condition is satisfied.
Scanner scanner = new Scanner(System.in);
boolean loop = true;
String choice = null;
while (loop) {
System.out.print("High, low or sevens (H/L/S):");
choice = scanner.nextLine();
if ("H".equalsIgnoreCase(choice.trim())
|| "L".equalsIgnoreCase(choice.trim())
|| "S".equalsIgnoreCase(choice.trim())) {
System.out.println("Correct Choice");
loop = false;
}
else
{
System.out.println("Wrong Choice");
}
}
System.out.print(choice);
char result;
while(true){
System.out.print("High, low or sevens (H/L/S):");
String entered = inScanner.nextLine();
System.out.print(entered);
if(entered.equals("H") || entered.equals("h")){
result = 'h';break;
}
else if (entered.equals("L") || entered.equals("l")){
result = 'l';break;
}
else if(entered.equals("S") || entered.equals("s")){
result = 's';break;
}else{
System.out.println("Invalid entry. Please try again using H/L/S!");
}
}
Hey you are not breaking out of the while loop at all. Did you see that ?
This is what you want. Here is the program to iterate over characters in a String. And convert them in lower case letter if they are H,L OR S.
package testproj;
import java.util.Scanner;
public class TestProj {
public static void main(String[] args) {
Scanner scanner = new Scanner("HLs");
String result = getHighLow(scanner);
System.out.println("Result :"+result);
}
private static String getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S):");
String entered;
String result = "";
boolean isCharFound = false;
String temp = "";
while (inScanner.hasNext()) {
temp = inScanner.next();
System.out.println(temp);
for (int index = 0; index < temp.length(); index++) {
entered =new Character(temp.charAt(index)).toString() ;
if (entered.equals("H") || entered.equals("h")) {
result = result + 'h';
isCharFound = true;
} else if (entered.equals("L") || entered.equals("l")) {
result = result + 'l';
isCharFound = true;
} else if (entered.equals("S") || entered.equals("s")) {
result = result + 's';
isCharFound = true;
}
if (!isCharFound) {
System.out.println("Invalid entry. Please try again using H/L/S!");
}
isCharFound = false;
}
}
return result;
}
}