Trouble with "do while" - java

this program expects a capital letter from user input. The input is saved in char variable c, after that converted to ascii, and then checked, if it really is a capital letter. When not, program should ask again. Problem ist, that command System.out.println("Write capital letter: ") is executed multiple times and it looks like that:
Write capital letter:
Write capital letter:
Write capital letter:
Write capital letter:
Write capital letter:
I want to have only one "Write capital letter: " on screen after every wrong input, and it needs to eb done with ascii table.
Thanks in advance.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int ascii;
char c;
do {
System.out.println("Write capital letter: ");
c = (char) System.in.read();
ascii = (int) c;
} while (ascii < 65 || ascii > 90 );

System.out.println("Write capital letter: ");
do {
c = (char) System.in.read();
// ascii = (int) c; // not needed if you are using the isUppercase() method
if(! Character.isUppercase(c)){
System.out.println("Write capital letter: ");
}
} while (! Character.isUppercase(c) );
As long as the condition is true, whatever is defined in the do block is executed. So, move the statements you want to execute only once out of the do block.

Why are you using System.in.read() when you have a BufferedReader variable set?
This will solve your issue. I am using your BufferedReader in variable.
while (true) {
System.out.println("Write capital letter: ");
int b = 0
while ((b = in.read()) != -1){
char c = (char) c;
if (Character.isUpperCase(c)) break;
}
//Carry on...
}

Related

Choosing a letter from the alphabet and putting quotation marks on it

I'm trying to make a program where it asks for a letter from the alphabet. Lets say I choose the letter "b". The "b" should be shown in quotation marks in the program. I'm trying to learn Java, I know HTML and CSS, but Java is new to me, so go easy.
So in practice:
Choose a letter:
d
abc"d"efghijklmnopqrstuvwxyz
I've figured out how to print the alphabet
import java.util.Scanner;
public class Characters {
public static void main(String[] args) {
char c;
for(c = 'a'; c <= 'z'; ++c)
System.out.print(c + " ");
}
}
(I have added scanner, because I'll ask the user for the letter)
A very concise example:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
char c = s.next().charAt(0);
for(char i = 'a'; i < 'z'; i++){
System.out.print(i == c ? "\""+c+"\"" : i);
}
}
}
Use java.util.Scanner's .next() to read the next word, then get the first character of the word.
Sample Run:
a
"a"bcdefghijklmnopqrstuvwxy
Since Java recognises quotation marks for text, you need to add a \ before each caracter to indicate to java that you wish for it to be part of the text. For example, if you want to show "b" with quotation mark, your final string is going to be a\"b\"cdefghijklmnopqrstuvwxyz
First, we would have to read the input char:
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0); // Get char
Then, I would make sure that our char is in the alphabet:
if(!('a' <= c && c <='z')) {
return; // NOT IN ALPHABET
}
If we got this far, we successfully read a character, which is in the alphabet.
Now, we can print out the modified alphabet.
for(char letter = 'a'; letter <= 'z'; letter++) {
if(letter == c) {
System.out.print("\"" + c + "\"");
}else {
System.out.print(letter);
}
}

Hangman: How to compare and replace a dash with a letter found

I am learning Java, I know it exists several solutions on stackoverflow but I am stuck. I am trying to create a basic Hangman.
I would like to know how Could I replace a dash with a letter found?
Here is a demonstration:
The word to search is:no
I enter the letter n
You have 5 attempts.
--
Enter your letter: n
I enter the letter o
You have 4 attempts.
--
Enter your letter: o
Idem.
You have 3 attempts.
--
Enter your letter:
Here is my code:
Scanner input = new Scanner(System.in);
char letter = 0; // declares and initialises letter
String[] words = {"yes", "no"}; // declares and initialises an array of words to guess
String word = words[(int) (Math.random() * words.length)]; // chooses random word
boolean[] found = new boolean[word .length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word.length(); i++) {
if ( found[i] ) {
System.out.print(word.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
attempts--;
}
I have to add a loop perhaps?
I share you my code here => https://repl.it/repls/PeriodicLegitimateMatrix
You can use the indexOf(char) method in the String class to check whether the character was in the word.
It should look like this:
while (attemps > 0) {
//...
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
int characterPosition = word.indexOf(letter);//use a loop because the character could appear in more than one position in the word
while (characterPosition != -1) {//if indexOf(char) returns -1 it means the char was not found
found[characterPosition] = true;
characterPosition = word.indexOf(letter, characterPosition);//this time search the character starting from the last position to find the next one
}
attempts--;
}

How can I concatenate the next two characters from a user input and print them?

I need to write a method nextCharacters that asks the user to input a character. The program should respond by printing the next two characters. For example, if the user enters the character e, the program should respond by printing fg to the console. You can assume that the character entered is not a whitespace character.
So far I have managed to get this way around it. Is there a more efficient way to do it? Also why can't I simply increment by doing firstChar++ and firstChar+=2;
public static void nextCharacters() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a character: ");
String first = input.next();
char firstChar = first.charAt(0);
char secondChar = (char) (firstChar + 1);
char thirdChar = (char) (firstChar + 2);
System.out.println("" + secondChar + thirdChar);
}

Console input and ENTER key with Java

I'm learning Java with the book: Java. A begginer's guide.
The book shows the following example:
// Guess the letter game, 4th version.
class Guess4 {
public static void main (String args[])
throws java.io.IOException {
char ch, ignore, answer = 'K';
do {
System.out.println ("I'm thinking of a letter between A and Z.");
System.out.print ("Can you guess it: ");
// read a character
ch = (char) System.in.read();
// discard any characters in the input buffer
do {
ignore = (char) System.in.read();
} while (ignore != '\n');
if ( ch == answer) System.out.println ("** Right **");
else {
System.out.print ("...Sorry, you're ");
if (ch < answer) System.out.println ("too low");
else System.out.println ("too high");
System.out.println ("Try again!\n");
}
} while (answer != ch);
}
}
Here is a sample run:
I'm thinking of a letter between A and Z.
Can you guess it: a
...Sorry, you're too high
Try again!
I'm thinking of a letter between A and Z.
Can you guess it: europa
...Sorry, you're too high
Try again!
I'm thinking of a letter between A and Z.
Can you guess it: J
...Sorry, you're too low
Try again!
I'm thinking of a letter between A and Z.
Can you guess it:
I think the output of the program should be:
I'm thinking of a letter between A and Z.
Can you guess it: a...Sorry, you're too high
Try again!
Without a \n between 'a' and '...Sorry, you are too high'. I don't know why apears a new line. The do-while erases it.
Thank you.
ch = (char) System.in.read();
actually reads a single character.
if the input is - a\n only the first character is read and stored in ch. which is a in this case.
do {
ignore = (char) System.in.read();
} while (ignore != '\n');
This is used to remove any unwanted characters.
Why did they use this?
We just need a single letter.
So if the user had given an input which is not a single character, like "example" and if your code didn't have the loop check.
First the ch becomes e, then x ....so on.
Even without the user entering a alphabet the previous input is considered to be entered.
what if only Enter(\n) was pressed
As even \n is considered a character it is also read. In the comparison the ASCII value of it is considered.
Have a look at this question. In which a user didn't check for the unnecessary characters and got an unexpected output.
Instead doing stuff char-by-char, you could easily utilize a Scanner:
replace
// read a character
ch = (char) System.in.read();
// discard any characters in the input buffer
do {
ignore = (char) System.in.read();
} while (ignore != '\n');
with
Scanner in = new Scanner(System.in); //outside your loop
while(true) {
String input = in.nextLine();
if(!input.isEmpty()) {
ch = input.charAt(0);
break;
}
}

passing a lowercase letter to uppercase equivalent without using toUpperCase () method

I've been trying and trying and there is no way.
I want to spend a lowercase letter to uppercase equivalent.
I know and know how to use the method toUpperCase () but I want to do without it.
This is my failing code:
import java.util.Scanner;
public class ConvertLetters {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.print("enter a lower case letter");
char letter = stdin.nextLine();
int letter2 = 'A' + (letter - 'a');
System.out.println("and we will refund your letter capitalized");
System.out.print("Your letter: " + letter);
System.out.print("upper case equates to:");
System.out.print(letter2);
}
}
You want to finish with a char
char letter = stdin.nextLine().charAt(0);
char letter2 = (char) ('A' + (letter - 'a'));
or
char letter2 = (char) (letter - 32);
I see two problems with this code. First, you assign nextLine(), which is a string. You may want something like
char letter = stdin.nextLine().charAt(0);
instead. Second, you print int, try
System.out.print((char)letter2);
With these changes, I think your code will give you better results.
Naturally, that won't work for non-ascii characters, anyway.

Categories

Resources