I'm trying to make it so that when the user enters anything but y/n it'll say error and when they enter n it'll say have a great day. This is what I have so far, but I keep running into trouble.
This is the assignment:
Write a program that gets an integer from the user, say x, and then
prints an x by x square, and it prints that square x number of times.
For example, if the user enters 4, your program will print a 4x4
square four distinct times. Specifics:
The user enters a value 3-15. Input validation: only accept 3-15.
Allow the user to repeat the program if desired. Input validation: Y
or N only, but also allow lowercase entries.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("*******************************************************\n"
+ "*******************SQUARE GENERATOR********************\n"
+ "*******************************************************\n"
+ "\nThis program will let you enter an integer between\n"
+ "3-15 and print out that many squares of that dimension.\n");
char answer = 'y';
while (answer == 'y' || answer == 'Y') {
System.out.println("Enter the square size --> ");
int x = keyboard.nextInt();
while (x < 3 || x > 15) {
System.out.println("Error: Select a number between 3 and 15 inclusive: ");
x = keyboard.nextInt();
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++) {
System.out.print("X");
}
System.out.println("");
}
System.out.println("");
}
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
}
answer = 'n';
while (answer == 'n' || answer == 'N') {
System.out.println("Program ending. Have a great day.");
}
keyboard.close();
}
}
You can solve this problem by only using one while loop. You use a break condition to inidicate that the loop should terminate (in your example if the user enters 'n').
Here is an example how I would try to solve this problem:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("*******************************************************\n"
+ "*******************SQUARE GENERATOR********************\n"
+ "*******************************************************\n"
+ "\nThis program will let you enter an integer between\n"
+ "3-15 and print out that many squares of that dimension.\n");
boolean exit = false; // define the boolean variable
char answer = 'y';
while (!(exit)) { // start the while loop
if (answer == 'y' || answer == 'Y') { // if the user enters 'y' proceed with your code
System.out.println("Enter the square size --> ");
int x = keyboard.nextInt();
while (x < 3 || x > 15) {
System.out.println("Error: Select a number between 3 and 15 inclusive: ");
x = keyboard.nextInt();
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++) {
System.out.print("X");
}
System.out.println("");
}
System.out.println("");
}
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
} else if (answer == 'n' || answer == 'N') { // if the user enters 'n' exit the program and the loop
System.out.println("Program ending. Have a great day.");
exit = true;
} else { // display an error message when something else is typed
System.out.println("You entered an unvalid char, please answer by saying Y/N!");
answer = keyboard.next().charAt(0);
}
}
System.out.println("Reached end of program!");
keyboard.close();
}
Since this looks like homework I won't post the full answer but you can change the
while (answer == 'n' || answer == 'N')
to
if (answer == 'n' || answer == 'N')
Also close the scanner inside the if block above. The else case to the above is where you would throw the error. Hope its clear.
EDIT
Another thing I would like to add is that you can remove answer = 'n'; before the if condition above. That will already be read by
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
Related
I want to apply this function in java. Inside while loop, you need to input number of repetition you want to input a number. if you input a number that equals to the number that you enter previously, it will repeat a loop and enter a number again. This code is not finish yet. I hope u understand what i want to achive. thank you
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == input){
System.out.println("It is already taken");
}
}
}
}
Let's use a temp variable to store the value of previous input. If new input is same as previous input, the iterator i should not increase, so we use i--
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
int temp=0;
int inputArray[] = new int[times];
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == temp){
System.out.println("It is already taken");
i--;
}else {
inputArray[i-2]=input;
}
temp=input;
}
}
The thing with that solution is that is only checks for the number just entered before the current one. I understood that you want to check that the number the user entered is unique and it has to be checked against every number that he/she has entered before.
See the code for that:
import java.util.Scanner;
import java.util.ArrayList;
public class testMe{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of times: ");
int times = scanner.nextInt();
int i = 0;
ArrayList<Integer> listWithEntries = new ArrayList<Integer>();
while (i < times){
System.out.print("Enter a number : ");
int input = scanner.nextInt();
if(listWithEntries.size() == 0){
listWithEntries.add(input);
i++;
} else {
for(int j = 0; j < listWithEntries.size(); j++){
if(input == listWithEntries.get(j)){
System.out.println("It is already taken!");
break;
}
if(j == listWithEntries.size()-1 && input !=
listWithEntries.get(j)){
listWithEntries.add(input);
i++;
break;
}
}
}
}
}
}
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int guesses = 0;
//Do I really need this part?
//Ask the user to enter a word and store it into an array
System.out.println("Please enter a word: ");
String wordToGuess = kybd.next();
char[] word = wordToGuess.toCharArray();
char[] underscore = new char[wordToGuess.length()];
for (int i = 0; i < wordToGuess.length(); i++) {
underscore[i] = '_';
}
System.out.println("You have 6 tries to guess the word:");
for ( int i = 0; i < wordToGuess.length(); i++) {
System.out.println(" " + underscore[i] + " ");
}
System.out.println("Please enter your guess: ");
char guess = kybd.next();
for (int i = 0; i < word.length; i++) {
if (guess == word[i]) {
underscore[i] = guess;
}
}
}
}
// I've gotten a little lost here.
I know this is not right at all but I'm hoping for some tips. Thanks so much!!
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kybd = new Scanner(System.in);
System.out.println("Please enter a word: ");
String wordToGuess = kybd.next();
char[] underscore = new char[wordToGuess.length()];
for (int i = 0; i < wordToGuess.length(); i++) {
underscore[i] = '_';
}
int wordLenToGuess = wordToGuess.length();
int unsuccessfulTries = 6;
while(wordLenToGuess >0 && unsuccessfulTries >0 ){
System.out.println();
for ( int i = 0; i < wordToGuess.length(); i++) {
System.out.print(" " + underscore[i] + " ");
}
System.out.println();
System.out.println("You have " +unsuccessfulTries+ " tries to make a guess");
System.out.println("Please enter your guess: ");
//kybd.nextLine();
char guess = kybd.next().charAt(0);
boolean iscorrect = false;
for (int i = 0; i < underscore.length; i++) {
if(wordToGuess.charAt(i) == guess)
{
underscore[i] = guess;
wordLenToGuess--;
iscorrect = true;
}
}
if(!iscorrect)
unsuccessfulTries--;
}
if(wordLenToGuess == 0)
System.out.println("YOU WIN!! :)");
else System.out.println("Sorry! You Lose :(");
}
}
Algorithm:
Keep trying till either entire word is guessed or 6 incorrect tries.
If correct letter is guessed, fill in the blanks '_' else decrement the number of tries
Exit loop when either entire word is guessed or all 6 tries are used up.
Inform user if he wins or loses.
Couple things that need to be addressed here include giving the user the option to guess either a letter or a word, having the game go on as long as the user has not yet guessed the word yet, and checking to see if the user guessed a letter he or she has already guessed (this last thing is optional but is good practice for error checking). Think about the condition that will keep the game going. The game won't end until the user guessed 6 times or managed to successfully guess the word. To check these conditions after each guess, we can use a while loop. To see if the user guessed the word correctly, we can use a boolean variable to keep track of this,
boolean wordHasBeenGuessed = false;
while(!wordHasBeenGuessed && guesses < 6)
//this loop reads "while the word has not been guessed yet and the user has not exceeded 6 guesses
To give the user the option to guess either a letter or a word, we need to present two scenarios using if statements,
System.out.println("Would you like to guess a letter or a word?");
String type = kybd.next();
if(type.toLowerCase().equals("letter"){
//do stuff to deal with this case here
}
else{
//do stuff to deal with this case here
}//of course this part can be customized anyway you'd like
In the end, it should look something like this,
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int guesses = 0;
//Ask the user to enter a word and store it into an array
System.out.println("Please enter a word: ");
String wordToGuess = kybd.next();
char[] word = wordToGuess.toCharArray();
char[] underscore = new char[wordToGuess.length()];
for (int i = 0; i < wordToGuess.length(); i++) {
underscore[i] = '_';
}
boolean wordHasBeenGuessed = false;
int numOfLettersFound = 0;
while(!wordHasBeenGuessed && guesses < 6){
System.out.println("You have " + (6-guesses) + " tries to guess the word:");
for ( int i = 0; i < wordToGuess.length(); i++) {
System.out.print(" " + underscore[i] + " ");
}
System.out.println("Would you like to guess a letter or a word?");
String type = kybd.next();
if(type.toLowerCase().equals(letter)){
System.out.println("Enter your guess");
char guess = kybd.next();
for (int i = 0; i < word.length; i++) {
if (guess == word[i]) {
underscore[i] = guess;
numOfLettersFound++;
}
}
if(numOfLettersFound == wordToGuess.length()){
wordHasBeenGuessed = true;
}
}
else{
System.out.println("Enter your guess");
String answer = kybd.next();
if(answer.eqauls(wordToGuess){
wordHasBeenGuessed = true;
}
}
guesses++;
}
//after the while loop is finished, tell the user whether or not he/she has won or not
if(wordHasBeenGuessed){
System.out.println("You won");
}
else{
System.out.println("You lost");
}
}
}
If you have any questions, feel free to ask.
This is simple Hangman game:
public static void main(String[] args) {
String[] words = {"writer", "that", "program"};
int wordNumber = (int) (Math.random() * words.length);
System.out.print("Enter a letter in word ");
for (int i = 0; i < words[wordNumber].length(); i++)
System.out.print('*');
System.out.print(" > ");
Scanner input = new Scanner(System.in);
char letter;
do {
letter = input.nextLine().charAt(0);
boolean asterisksInWord = false;
String[] discoveredElements = new String[words[wordNumber].length()];
int countOfTries = 0;
int arrayCount = 0;
int asteriskCount = 0;
System.out.print("Enter a letter in word ");
do {
asterisksInWord = false;
boolean contain;
if (asteriskCount != 1) {
asteriskCount = 0;
for (char item : words[wordNumber].toCharArray()) {
contain = Arrays.asList(discoveredElements).contains(String.valueOf(item));
if (contain) {
System.out.print(item);
} else if (item == letter) {
System.out.print(item);
discoveredElements[arrayCount] = String.valueOf(item);
arrayCount++;
} else {
System.out.print('*');
asterisksInWord = true;
asteriskCount++;
}
}
}
if (asterisksInWord) {
System.out.print(" > ");
letter = input.nextLine().charAt(0);
if (asteriskCount != 1)
System.out.print("Enter a letter in word ");
} else
System.out.println("The word is " + words[wordNumber] +
" You missed " + (countOfTries + 2 - words[wordNumber].length()) + " time(s)");
countOfTries++;
} while (asterisksInWord);
System.out.print("Do you want to guess another word? Enter y or n >");
} while (input.nextLine().charAt(0) == 'y');
}
The log of it's run is
Enter a letter in word **** > t
Enter a letter in word t**t > h
Enter a letter in word th*t > a
The word is that You missed 0 time(s)
Do you want to guess another word? Enter y or n >y
y
Enter a letter in word **** >
My question is why does it ignores first symbol 'y' when asking "Do you want to guess another word?".
I'tried to create some test programs with same do-while conditions but they don't ask for character 2 times like that program.
The program asks for your input two times, because you have programmed it like that. After printing - "Do you want to guess another word? Enter y or n >" - you do input.nextLine() inside the while condition as well as as the first statement after do , so it asks for input twice.
Maybe you can move the question Enter the letter in the word to the inner do loop instead of doing that in the if condition if (asterisksInWord) { .
Also, according to your current logic, it does not ignore your first symbol, that is the real one that decides whether to exit the loop or not, the next input is actually your first guess.
I have the following homework problem:
Q1. Use nested for loops statements to draw empty boxes of any character (input from user). The boxes have the same number of rows and columns (input from the user; valid range: 5 to 21). Test for errors in input (including type)
SAMPLE OUTPUT:
Do you want to start(Y/N): y
How many chars/last row? n
Not an integer! Try again! How many chars/last row? fgfgfg
Not an integer! Try again! How many chars/last row? 7.6
Not an integer! Try again! How many chars/last row? 34
ERROR! Valid range 5 - 21. How many chars/last row? 7
What character? k
Do you want to continue(Y/N): y
I've written the below code, but it doesn't exit when I hit 'n' or 'N', and I'm not sure why. How would I fix this?
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
char answer = 'n';
int row = 0;
char output = 'k';
do {
System.out.println("DO YOU WANT TO START Y OR N?");
answer = input.next().charAt(0);
System.out.println("enter the number of rows");
while (!input.hasNextInt()) {
System.out.println("Not an integer,try again ");
input.next();
}
row = input.nextInt();
while (row < 5 || row > 21) {
System.out.println("ERROR! Valid range 5 - 21. How many chars/last row?");
row = input.nextInt();
}
System.out.println("WHAT CHARACTER?");
output = input.next().charAt(0);
for (int i = 0; i < row; i++) { //nested for loop to create the box
System.out.print(output);
}
System.out.println();
for (int i = 0; i < row - 2; i++) {
System.out.print(output);
for (int j = 0; j < row - 2; j++) {
System.out.print(" ");
}
System.out.print(output);
System.out.println();
}
for (int i = 0; i < row; i++) {
System.out.print(output);
}
System.out.println();
System.out.println();
System.out.println("DO YOU WANT TO CONTINUE ? Y OR N");
answer = input.next().charAt(0);
} while (answer == 'Y' || answer == 'y');
input.close();
System.out.println("game stop");
}
You need to add condition for N after Do you want to start(Y/N): and Do you want to continue(Y/N):
System.exit(0) is used to terminate the program.
Put this code
System.out.println("DO YOU WANT TO START Y OR N?");
answer = input.next().charAt(0);
if(answer == n || answer == N){
System.exit(0);
}
And this for Do you want to continue(Y/N):
System.out.println("DO YOU WANT TO CONTINUE ? Y OR N");
answer = input.next().charAt(0);
if(answer == n || answer == N){
System.exit(0);
}
Edit
If you want to print 'Game Stop' if the answer is N, then use Thread.sleep(timeInMilliseconds); before System.exit(0)
if(answer == n || answer == N){
Thread.sleep(5000); //This will make console wait for 5 seconds before exiting.
System.out.println("Game Stop."); //game stop will be printed for 5 seconds
System.exit(0);
}
The simplest way to do this is:
Check for input "N" INSIDE the loop, and break out of the while loop, possibly like so:
if ((answer == 'n') || (answer == 'N')) {
break;
}
Also, you're checking for y/n input 2 times in this program. A better method of writing this would be to use a normal while loop instead of a do-while loop; clearly, in the question if you input N right at the beginning you shouldn't be running through the program at all. A Do-While loop is useful to ensure that the program runs at least once (which is not what should happen here; the program should only run if the input is valid eg: "y"). While using a DW-loop is "ok", a while loop would serve the purpose better here.
Your loop can be written like so instead:
// you need this line to initially print the y/n question.
System.out.println("DO YOU WANT TO START Y OR N?");
// get an input and check if it is not n
while (Character.toUpperCase(input.next().charAt(0)) != 'N') {
// do stuff here
System.out.println("DO YOU WANT TO CONTINUE ? Y OR N"); // ask for next input
}
I'm doing lottery game for my assignment (user inputs 6 number, i will generate 8 unique winning numbers and 2 last numbers are supplementary). I need help with user input checking if input numbers are from 1 to 45 and input must be int, when input is not integer it throws an error.
This programming way is procedure way, how can i change it into object oriented way? I know that I must make methods in another java file and then link it back to this main. Can you suggest me how to do it?
I have tried try and catch, if and else (for input check) but i don't know how to check user input when it's in array. Thank you for help.
Here is my code:
class Lottery {
public static void main ( String[] args ) {
System.out.println("\nWelcome to the Lottery game.");
System.out.println("You can enter numbers from 1 to 45.");
// User input into an array
int[] input = new int[6];
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease enter your 6 lucky numbers: ");
for(int j = 0; j < 6; j++) {
input[j]=scanner.nextInt();
}
int check = scanner.nextInt();
if(check < 0 && check > 45) {
System.out.println("\nERROR: Please enter only numbers from 1 to 45!");
}
// Printing out unique winning numbers from random generator
System.out.println("\nWinning numbers: ");
MultiRandomGenerator mrg = new MultiRandomGenerator();
int[] set;
set = mrg.getSet();
for (int i = 0; i < set.length; i++) {
System.out.print(set[i] + " ");
}
// Loops for counting how many numbers user has guessed right
int count = 0; // for 6 numbers
int scount = 0; // for 2 last supplementary numbers
for(int i = 0; i < input.length; i++) {
for(int k = 0; k < set.length; k++) {
if (k < 6) {
if (set[k] == input[i]) {
count++;
} else {
if (set[k] == input[i]) {
scount++;
}
}
}
}
}
System.out.print("\n\nYou guessed right " + count + " winning numbers.");
System.out.print("\nYou guessed right " + scount + " suplementary numbers.");
// If statments for printing out winning prizes
if (count == 6) {
System.out.println("\nYou have won 1st price!");
} if (count == 5 && scount == 1) {
System.out.println("\nYou have won 2st price!");
} if (count == 5) {
System.out.println("\nYou have won 3st price!");
} if (count == 4) {
System.out.println("\nYou have won 4st price!");
} if (count == 3 && scount == 1) {
System.out.println("\nYou have won 5st price!");
} if (count == 1 && scount == 2) {
System.out.println("\nYou have won 6st price!");
} else {
System.out.println("\nSorry, you didn't won anything.");
}
}
}
Sample code to go through array and find the invalid user input.
set = mrg.getSet();
String[] userDataStatus = new String[45];
for (int i = 0; i < set.length; i++)
{
try
{
String inputdata = set.get(i);
if(inputdata != null && inputdata.trim().length() > 0)
{
int currentNumber = Integer.parseInt(userdata);
userDataStatus[i] = "Y";//Y represent valid number
}
}
catch (NumberFormatException ex )
{
userDataStatus[i] = "N";//If it throws exception then save as 'N'
}
}
Use the above String array and display error messaage to users.
You can check in your loop, something like
int val;
try
{
input[j] = Integer.parseInt( scanner.nextString() );
}
catch (NumberFormatException ex )
{
}