How to manually shuffle letters in a String - java

I am Writing a game/java program that needs to take a word from a .txt file, then jumble the letters up and ask the user to guess what word it is. I am having two problems:
First is that I receive this error message when I run it:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Proj4.main(Proj4.java:20)
The second problem I am having is jumbling the word. I cannot figure out how to do that without using the shuffle command (which I cannot use).
Here is my code:
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Proj4 {
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new File ("words.txt"));
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
int lengthList = Integer.parseInt(word[0]);
Scanner s = new Scanner(System.in);
Random randomNumber = new Random();
int i = randomNumber.nextInt(lengthList); //picks a word at random. assigns to "word"
String currentWord = word[i];//picks a word at random. assigns to "currentWord"
int turnScore = 10, finalScore = 0;
char input;
String guess ="a";
do { //do loop for whole program looping
turnScore = 10;
do { //do loop for guessing correct
do{
System.out.println("Current Puzzle: " + currentWord);
System.out.println("Current points for this word: " + turnScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
input = s.nextLine().charAt(0); //assigns input to first letter entered by user
Character.toLowerCase(input); //puts input to lower case
if(input != 'g' && input != 'G' && input != 'h' &&
input != 'H' && input != 'n' && input != 'N' &&
input != 'Q' && input != 'q'){
System.out.println("Invalid Entry. Please input g, n, q or h only! \n ");
}
} while (input != 'g' && input != 'G' && input != 'h' && input != 'H' &&
input != 'n' && input != 'N' && input != 'Q' && input != 'q'); //end do while loop (ask for input)
if (input == 'g') {
System.out.println("Enter Your guess: ");
guess = s.nextLine();
System.out.println("your guess is: " + guess + "\n\nThe word is: " + currentWord);
if (guess.equalsIgnoreCase(currentWord)) {
System.out.println("You Guessed Correct");
System.out.println("Your Score for this word is: " +turnScore );
finalScore = finalScore + turnScore;
}//end if guess = currentWord
else
{
if (turnScore <= 0)
{
turnScore = 0;
}//end if turn score >=0
else
{
turnScore -= 1;
}//end else turn score minus 1.
System.out.println("Nope, Sorry \n\n");
}//end else guess not = to currentWord.
}//end if user input = G.
else if (input == 'n')
{
i = randomNumber.nextInt();
currentWord = word[i];
turnScore = 10;
}//end new word if
else if (input =='h')
{
turnScore = turnScore/2;
Random ranNum = new Random();
int randomLetter = ranNum.nextInt(5);
char hint = currentWord.charAt(randomLetter);
System.out.println("the Letter at spot " + (randomLetter +1) + " is " + hint);
}//end of if input = h
else if (input == 'q')
{
finalScore = finalScore + turnScore;
System.out.println("Goodbye!");
System.out.println("Final Score: " + finalScore);
System.exit(0);
}//end else if for input = Q.
}while (!guess.equalsIgnoreCase(currentWord));
}while (input != 'q');
System.out.println("Your Final Score is: " + finalScore);
System.out.println("Goodbye!");
inFile.close();
}//End main
}//end class

Your exception is caused by these lines of code:
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
//inFile no longer has next, will break when the for loop is entered
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
The easy way to fix this is to redeclare the inFile and read from beginning again.
The best way to fix this is to use a dynamically sized ArrayList:
int counter = 0;
ArrayList<String> word = new ArrayList<String>();
while (inFile.hasNext()) {
word.add(inFile.nextLine());
counter++;
}
This also makes your randomizing much more easy since you can do something sneaky with it.
Here's the documentation on ArrayList.
The key, not the solution, to your second question lies add(int index, E element)
There is a way to shuffle on the fly as you read. You should figure that out, and if you get stuck, then come back.

Related

For loop is printing out multiple print statements

I'm making a program for class which prints out the number of vowels in a word and any help would be appreciated. Currently, the program prints out the correct number of vowels but also prints out the print statement, "vowels:" multiple times before. I've tried moving the print statement and the braces around but it says "error: 'else if' without 'if'". I'm completely new to Java so sorry if the solution is in plain sight. Thank you in advance :)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels= 0;
int l;
l= text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i,i+1);
if (wordPRT.compareToIgnoreCase("a")==0 || wordPRT.compareToIgnoreCase("e")==0||
wordPRT.compareToIgnoreCase("i")==0
|| wordPRT.compareToIgnoreCase("o")==0
|| wordPRT.compareToIgnoreCase("u")==0){
vowels++;
System.out.println("vowels: " + vowels);
}
else if(vowels<1){
System.out.print("no vowels");
}
}
}
}
You are printing everything in a for loop instead of count vowels and print at the end.
try something like:
int vowelsCounter = 0;
for(...) {
... logic to count the vowels
if(isvowel(string.charAt(i)){
vowelsCountr++;
}
}
if(vowelsCounter > 0 ) {
printSomething
}
else {
print something else
}
Also You should not use subString for this kind of a loop but string.charAt(i)
Move the print statements out of the for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels = 0;
int l;
l = text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i, i + 1);
if (wordPRT.compareToIgnoreCase("a") == 0 || wordPRT.compareToIgnoreCase("e") == 0
|| wordPRT.compareToIgnoreCase("i") == 0 || wordPRT.compareToIgnoreCase("o") == 0
|| wordPRT.compareToIgnoreCase("u") == 0) {
vowels++;
}
}
if (vowels >= 1) {
System.out.println("vowels: " + vowels);
} else {
System.out.print("no vowels");
}
}
}
A sample run:
Enter text: Hello
vowels: 2

Stuck in logic for movie guess game in java (by udacity)

I am making a movie guessing game(much like hangman but doesn't contain the stick figure and stuff) on Java that takes input from the user, letter by letter. I am stuck where I want the letter entered to replace all instances of that letter in the title of the movie. My code is not working completely.
Later, I am gonna apply the logic that stops the user from entering the same letter again. But at the moment I need to fix this particular issue. Any help?
This is the game process function in my game class.
public void GameProcess(char[] dashedarray) {
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
while (run) {
if (dashedarray[i] == ' ') {
spaces++;
i++;
continue;
} else {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if (moviename.charAt(i) == guess) {
dashedarray[i] = guess;
correct++;
}
else if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
}
}
else
{
wrong++;
}
}
i++;
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}
}
You don't need i at all. spaces is to count the number of spaces in your answer, which does not need to be guessed. You should do that outside of the loop.
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
for (int i = 0; i < dashedarray.length; i++) {
spaces++;
}
while (run) {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
boolean match = false;
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
match = true;
}
}
}
// It matched nothing, this input is wrong.
if (!match) {
wrong++;
}
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}

Hangman stats error

My code does not show the number of wins, losses and numberOfGames I had played.
I've been trying to fix it for the last month and I'm going nowhere!
import java.util.Random;
import java.util.Scanner;
public class HangmanP2 {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
String first, reverse = "";
String second, reverse2 = "";
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Hangman!");
System.out.println("Enter your first name.");
first = in.nextLine();
System.out.println("Enter your last name to play.");
second = in.nextLine();
int length = first.length();
int length2 = second.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + first.charAt(i);
reverse = reverse.substring(0,1).toUpperCase() + reverse.substring(1).toLowerCase();
for ( int i = length2 - 1 ; i >= 0 ; i-- )
reverse2 = reverse2 + second.charAt(i);
reverse2 = reverse2.substring(0,1).toUpperCase() + reverse2.substring(1).toLowerCase();
System.out.println("Your name entered in reverse is: "+reverse+" "+reverse2);
startGame(reverse,reverse2);
}
public static void startGame(String reverse,String reverse2){
Random rnd = new Random ();
Scanner user = new Scanner (System.in);
String guess = "";
String message = "";
int count = 1;
boolean quit = false;
String fullWord = "";
int wins=0;
int loss=0;
int numberOfGames=0;
int guessC = 5;
String usedLetters ="";
String remainingLetters ="";
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int hinter = 0;
int z = rnd.nextInt(10);
int k = rnd.nextInt(2);
String words[][] = {{"earth","stars","light",
"world","about","again",
"stars","light","music",
"happy","water","amber",
"apple","piano","green",
"mouth","suger","stone",
"japan","china","after","lemon",
"grand",
"lives","twice","print"},{"smile",
"puppy","latin","vegan","phone","april",
"south","house","hangs","woman",
"power","today","india","night","candy",
"forum","birth","other","chris","irish",
"paste","queen","grace","crazy","plant",
"knife","spike","darth","vader","eagle",
"egypt","range","fists","fight","glory",
"March","smart","magic","codes","rolls",
"match","honor","glass","board","teams",
"bully","zebra","under","mango","brain",
"dirty","eight","zeros","train","cycle",
"break","necks","terms","slide","large"},{"stake","guess","wrong","anime","stick","outer","input"},{ "thing","write","white","black"}};
//Prints info of the game and topic that as been selected
System.out.println("Welcome to Hangman"+" "+reverse+" "+reverse2);
//This prints the '-' and spaces for the first run of the game only
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
//Nothing will change, this prints information to the user about his current status in-game.
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
//The loop that will continuously run the game, until the user fails or does not want to play again.
do{
//The following variable's make sure there is not stacking from previous data when the loop runs again.
remainingLetters = "";
count = 0;
//Ask the user for a letter to guess
System.out.println("\nEnter a letter to guess the word): ");
guess = user.nextLine();
//The following for-loop converts ASCII table [A-Z] to actually characters and if the player used a letter it will not show up or add to the string each run of the do-loop.
for(int x = 65; x < 91;x++){
Character current = new Character ((char)x);
String current2 = current.toString();
if(!usedLetters.contains(current2)){
remainingLetters += current;
}
}
//Converts the user's first character to a string which is converted into another character and again converted into a String (Seem's useless) but i used it this way cause i was getting an error.
Character convert = new Character (guess.charAt(0));
Character conv = new Character (convert);
String converted = convert.toString();
//The letters the player uses will be added to a string, if it has not already been added and only if it is a letter.
if(!usedLetters.contains(converted) && conv.isLetter(convert)){
usedLetters+=guess.charAt(0);
}
//Inside this for-loop it turns our word into a String and the user's first character into a string.
for(int index = 0; index < words[z][k].length();index++){
//This is a helper
count++;
//Conversion of variables
Character current2 = new Character ( words[z][k].charAt(index));
String current = current2.toString();
Character current3 = new Character (guess.charAt(0));
String current4 = current3.toString();
String current5 = current4.toUpperCase();
String current6 = words[z][k].toUpperCase();
//If the players gets a letter correct, do the following.
if(current4.equalsIgnoreCase(current))
{
//Add's on to the previous string from where the player got it correct and change it to the correct letter instead of a '-'.
message = message.substring(0,index) + guess + message.substring(index + 1);
}
//If the player gets it wrong and the helper variable is equal to 1 (so that it does not follow the loop of the for-loop and it is not one of the special characters in the game('!' or '?').
if(!current6.contains(current5) && count == 1 && guess.charAt(0) != '?' && guess.charAt(0) != '!'){
guessC--;
}
}
//Prints information to the user of their current topic
//The secret word the player has to guess
System.out.println("Secret word: \t\t" + message.toUpperCase());
//The letters in the alphabet that have not been used yet
System.out.print("\nLetters remaining: ");
System.out.print(remainingLetters.toUpperCase() + "\n\n");
//This will print a message to the user, telling them information on using a hint or the hint itself.
//Letters the user has used since the game session has been running
System.out.print("\nLetters Used: ");
System.out.print(usedLetters.toUpperCase() + "\n");
//The amount of guesses the player has left
System.out.println("\nGuesses Remaining: " +guessC );
//If the player enters a '?' it will do the following.
if(guess.charAt(0) == '?'){
if(hinter <2){
//Displays what is in the array and information about the delay, while losing guesses.
hinter++;
System.out.print("\nHint will appear after next guess! \n");
guessC -=2;
}
}
//If the user guesses the word correct
if(message.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user ask to guess the entire word it is stored in a separate variable and make quit equal to true.
if(guess.charAt(0) == '!')
{
System.out.print("\nEnter the secret word: ");
fullWord = user.nextLine();
//if the user guesses the word correct then it will tell the user they are correct and make quit equal to true.
if(fullWord.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user does not get it right it will tell the user they are wrong and make quit equal to true.
else{
System.out.println("YOU ARE INCORRECT! the word is: " + words[z][k] + " ");
loss++;
quit = true;
}
}
//If the guesses counter equal 0 then it will tell them that they have lost and make quit equal to true.
if(guessC == 0){
System.out.println("GAME OVER! The secret word was [ " + words[z][k] + " ]!");
loss++;
quit = true;
}
//This is what happens when quit eventually becomes true, the user is asked if they would like to play again.
if(quit == true){
System.out.println("\nWould you like to play again (Y or quit)? ");
System.out.println("\nOr type [stats] to check your work");
guess = user.nextLine();
//If they do want to play again, they will need to enter Y and if they do it will give them another word to guess and resets there information so that there will be no overlap.
if(guess.equalsIgnoreCase("Y")){
quit = false;
z = rnd.nextInt(10);
k = rnd.nextInt(2);
guess = " ";
guessC = 6;
message = "";
usedLetters = "";
hinter = 0;
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
}
if(guess.equals("stats")){
printGameStats(wins,loss,numberOfGames);
}
else{
//If the user enters 'N' then they will be told the following and the scanner will be closed.
System.out.println("THANK YOU FOR PLAYING HAVE A GOOD DAY!");
user.close();
}
}
//end of the while loop which will only stop if quit equals true.
}while(quit != true );
}
private static void printGameStats(int wins,int loss,int numberOfGames) {
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
// Print titles
System.out.printf("| %6s | %6s | %12s |\n",
"WINS", "LOSSES", "GAMES PLAYED");
// Line
System.out.print("|");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(16);
System.out.print("+");
printDashes(18);
System.out.println("|");
// Print values
System.out.printf("| %6d | %6d | %12d |\n",
wins, loss, numberOfGames);
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
}
private static void printDashes(int numberOfDashes) {
for (int i = 0; i < numberOfDashes; i++) {
System.out.print("-");
}
}
}

Simple game of hangman with two character arrays. They get six tries. First user enters a word the second user guesses the word through _ blanks

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.

Checking for user input to be only integers in Java

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 )
{
}

Categories