I'm writing a method that checks that 1 of 3 letters has been entered.
The problem is I can't get the method to return the char.
The char variable in initially read into Scanner and entered into an array.
Here is where it is read in,
//get house Type and send into array
System.out.println("Property " +numProperty+ " : Terraced, Semi-Detached, Detached: (T/S/D)");
houseType [i] = readLetter(input.next().charAt(0));
input.next().charAt(0);
And this is the method readLetter
public static char readLetter(char input){
if(input != 'T'||input != 't'||input != 'S'||input != 's'||input != 'D'||input != 'd')
System.out.println("Invalid input! Enter option T, S or D? ");
else
return input;
}
The error is
The method must return a result of type char.
Try this:
public static char readLetter(char input){
if(input != 'T'&& input != 't'&& input != 'S'&&input != 's'&&input != 'D'&&input != 'd')
{
System.out.println("Invalid input! Enter option T, S or D? ");
return 0; //or something that signals invalid input
}
else
{
return input;
}
}
In the readLetter method you must return value in both cases, for example:
public static char readLetter(char input) {
if(input != 'T' && input != 't' && input != 'S' && input != 's' && input != 'D' && input != 'd') {
System.out.println("Invalid input! Enter option T, S or D? ");
return 0;
} else {
return input;
}
}
This will return 0 if input != 'T' && input != 't' && input != 'S' && input != 's' && input != 'D' && input != 'd'. You need to handle that in your main method, something like this:
System.out.println("Property " +numProperty+ " : Terraced, Semi-Detached, Detached: (T/S/D)");
char ch = readLetter(input.next().charAt(0));
if ( ch != 0 ) {
// the input was valid
houseType[i] = readLetter(input.next().charAt(0));
}
input.next().charAt(0);
Update: as someone noticed your condition input != 'T'||input != 't'||input != 'S'||input != 's'||input != 'D'||input != 'd' will always return true (ie. your input will always be illegal) but the fix is to replace || into && (change ORs into ANDs).
I edited the code to reflect that.
You are missing the case when the user enters an invalid value.
What the method is supposed to return in this case?
IMO, this method should return true or false indicating wheter the passed input is valid(T,S or D) or not.
You are doing this:
if(input != 'T'||input != 't'||input != 'S'||input != 's'||input != 'D'||input != 'd')
System.out.println("Invalid input! Enter option T, S or D? ");
else
return input;
so since you are not using {}, then the code is returning only if the condition is not met.
so your compiler complains since that method is not always returning a char...
Related
I want to take input from User in String in which only alphabets, dot(.) and Space is allowed. If User enter any other character expect these, my program should take input from user again. It should continue this process until the user enter the right input(which i want). And at any point if user enter right input it move's further. I tried the given code but it is not working.
import java.util.Scanner;
public class TourPlanner{
public static boolean validname(String name){
String nameUp=name.toUpperCase();
for(int i=0;i<nameUp.length();i++){
char charUp=nameUp.charAt(i);
if(charUp=='A' || charUp=='B' || charUp=='C' || charUp=='D' || charUp=='E' || charUp=='F' || charUp=='G' || charUp=='H' || charUp=='I' || charUp=='J' || charUp=='K' || charUp=='L' || charUp=='M' || charUp=='N' || charUp=='O' || charUp=='P' || charUp=='Q' || charUp=='R' || charUp=='S' || charUp=='T' || charUp=='U' || charUp=='V' || charUp=='W' || charUp=='X' || charUp=='Y' || charUp=='Z' || charUp=='.' || charUp==' '){
return true;
}
}
return false;
}//valid name
public static void intro(String name, Scanner in){
validname(name);
while(validname(name)==false){
System.out.print("*** Please Enter Name Correctly ***\n");
System.out.print("What is your Name? ");
name=in.nextLine();
}
String designation;
System.out.print("Nice to meet you "+name+" Where are you travelling to? ");
designation=in.nextLine();
System.out.print("Great! "+designation+" sounds like a great trip.");
}//intro
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("**** Welcome to tour Planner ****\n");
System.out.print("What is your Name?");
String name=in.nextLine();
intro(name,in);
System.out.println("\n\n********************************************\n");
}//main
}
public static boolean validname(String name){
boolean boo = true;
String nameUp=name.toUpperCase();
for(int i=0;i<nameUp.length();i++){
char charUp=nameUp.charAt(i);
if(charUp!='A' && charUp!='B' && charUp!='C' && charUp!='D' && charUp!='E' && charUp!='F' && charUp!='G' && charUp!='H' && charUp!='I' && charUp!='J' && charUp!='K' && charUp!='L' && charUp!='M' && charUp!='N' && charUp!='O' && charUp!='P' && charUp!='Q' && charUp!='R' && charUp!='S' && charUp!='T' && charUp!='U' && charUp!='V' && charUp!='W' && charUp!='X' && charUp!='Y' && charUp!='Z' && charUp!='.' && charUp!=' '){
boo = false;
}
}
return boo;
}//valid name
once a method encounters with "return", it stops working and doesn't check other conditions. In your code, your method checks the first letter and decides that it is valid, it returns true and does not check other characters. Because of that, I modified your code and the method creates a boolean value which is initially true. And checks whether an invalid character occurs in input string. After whole loop; if not, it returns true but if it does see an invalid character, boolean value becomes false and at the end of the method, you return it after checking all characters.
Note: String library has some useful functions that allows you to check whether a char is alphabetic, numeric etc. You don't need to write all those characters into an if condition.
Can anyone explain why the while loop ask whatNight twice? and how to reprompt invalid user input if user input something other than 'r' or 'c'
for(int x = 1; x <= inputInt; x++) {
char whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0);
boolean pleasework = whatNight == 'c' || whatNight == 'C';
boolean imbeggingu = whatNight == 'r' || whatNight == 'R';
boolean doesNotWork = whatNight != 'c' && whatNight != 'C' && whatNight != 'r' && whatNight != 'R';
//why does the while loop ask twice even if u enter c or r?
while(pleasework || imbeggingu || doesNotWork) {
if(doesNotWork)
JOptionPane.showMessageDialog(null, "INvalid letter");
whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0);
//reprompt not storing in whatNight variable :/
if(pleasework)
JOptionPane.showMessageDialog(null, "You entered c for carnight");
else if(imbeggingu)
JOptionPane.showMessageDialog(null, "You entered r for regular night");
break;
}
To answer your question I would recommend you to debug your values as a first step e.g
System.out.println(pleasework);
Your concepts logic is pretty off aswell and you should rethink how you want to handle the issue. For example when your input is not C or R you ask for a new input but you dont set any boolean according to it.
this should work!
for(int x = 1; x <= inputInt; x++) {
char whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0);
whatNight = checkInput(whatNight);
boolean nightC = whatNight == 'c' || whatNight == 'C';
boolean nightR = whatNight == 'r' || whatNight == 'R';
if(nightC) {
JOptionPane.showMessageDialog(null, "You entered c for carnight");
} else if(nightR) {
JOptionPane.showMessageDialog(null, "You entered r for regular night");
}
}
---------------------------------------------------------------------
private char checkInput(char input) {
if(input == 'c' || input == 'C' || input == 'r' || input == 'R') {
return input;
}
char whatNight = JOptionPane.showInputDialog("You entered a wrong letter, enter either c or r for what type of night it was").charAt(0);
return checkInput(whatNight);
}
If you dont understand something let me know and I'll explain!
I have a method that checks if the user is a student, but I can't get it validate the conditions.
char custStud = '0';
Scanner input = new Scanner(System.in);
do{
System.out.println("Are you a student? (Type Y or N): ");
custStud = input.next().charAt(0);
custStud = Character.toLowerCase(custStud);
}
while (custStud != 'y' || custStud != 'n');
When I fire up this program, it does not break the loop, even if 'y' or 'n' are entered. I suspect custStud might have accidentally changed types when changed to lowercase, but I'm not sure.
How can I make this loop work properly?
while (custStud != 'y' || custStud != 'n') is always true, since custStud can't be equal to both 'y' and 'n'.
You should change the condition to:
while (custStud != 'y' && custStud != 'n')
You've mistaken here:
while (custStud != 'y' || custStud != 'n');// wrong
while (custStud != 'y' && custStud != 'n');// correct
Try running this code:
char custStud = '0';
Scanner input = new Scanner(System.in);
do{
System.out.println("Are you a student? (Type Y or N): ");
custStud = input.next().charAt(0);
custStud = Character.toLowerCase(custStud);
}
while (custStud != 'y' && custStud != 'n');
System.out.print("\n answer:"+custStud);
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am just finishing my program, but I still have one problem left that I can't seem to find an answer too. I have been looking through already asked questions but I couldn't find something that specifically answers my question in this case. This is a program that lets the user input a string and then it counts how many vowels and consonants etc. And after this the user gets an option to repeat the program and input a new string if he/she press y, the program quits if he/she press n etc. The only thing that is not working is if the user presses y to repeat the program, it then prints out that there are 0 vowels and consonants etc. I know that it is something in the beginning of my code where I have int consonant_count=0 for example, I just can't figure out what to move and where to move it. Ps. this shouldn't be flagged as a duplicate since I didn't know that nextLine was the problem. Here is the code:
import java.util.Scanner;
public class loop2
{
public static void main (String[] args)
{
Scanner inputReader = new Scanner (System.in);
char result='y';
do {
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++)
{
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' || chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
// Kod f ̈or hantering av repetition
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.next();// H ̈amta anv ̈andarens svar.
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
result='y';
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
}
while (result == 'y'); // Observera semikolon!
}
}
You should use the nextLine() when reading input from the user, this grabs everything including the end of line character '\n' which is what gets left over after your next() call and then nextLine() grabs the '\n' which gives you the counts of 0, 0 for vowels and consonents
Scanner inputReader = new Scanner (System.in);
char result='y';
while(result == 'y')
{
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++)
{
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' || chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
//wrap your play again logic in another do/while where you
// ask for y or n until they enter either one
do {
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.nextLine();//read the entire next line <----
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
} while (result !='y' && result !='n');
}
I am trying to get a valid input of "y", "Y", "n" , or "N".
If the input is not valid (for example any word that starts with a "y" or "n") I want it to re-prompt the user for input.
So far I have:
while (again.charAt(0) != 'N' && again.charAt(0) != 'n' && again.charAt(0) !='Y' && again.charAt(0) != 'y' ) {
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
if (again.charAt(0)== 'N' || again.charAt(0) == 'n') {
active = false;
} else {
if (again.charAt(0)== 'Y' || again.charAt(0) == 'y'){
active = true;
random = (int) (Math.random () *(11));
}
}
The problem I am having is if I enter any word that starts with the letter "y" or "n" it senses it as valid input (since it is the character at slot 0). I need help fixing this so I can re-prompt the user when they enter a word that starts with a "y" or "n".
Thanks!
Assuming again is a string containing the complete user input, you could use:
while (!again.equals("N") && !again.equals("n") ...
The .equals() method will match only if the entire string matches.
You could just test to make sure the length of the input is 1:
again.length() == 1
But a better approach might be:
while (! (again.equalsIgnoreCase("n") || again.equalsIgnoreCase("y"))) {
...
}
or even
while (! again.matches("[nyNY]")) {
...
}
One of the way would be:
First check again String length is only ONE character. If not, ask again.
if(again.length() ==1)
{
while (again.charAt(0) != 'N' && again.charAt(0) != 'n' && again.charAt(0) !='Y' && again.charAt(0) != 'y' ) {
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
.....
}else
{
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
It sounds like what you want is:
while (!again.equals("N") && !again.equals("n") && !again.equals("Y") && !again.equals("y") ) {
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
This way you can also easily add Yes/No, etc later if you want.
Regex could be an alternative to have strict input checks. Following piece of code validates y or n ignoring the case.
while (!again.matches("(?i)^[yn]$")){
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
active = (again.equalsIgnoreCase("Y"))? true : false;