how to recognise capital letters and not just lower case - java

Hi i have done this program it works fine except if the user tries to write in capital letters i tried .toUpperCase but it still closes the program if you try to use capital letter to search can anyone help please thank you
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class database
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//my arrays
static String country [] = new String[1000];
static String capital [] = new String[1000];
static double population [] = new double[1000];
static List<String> countriesList = Arrays.asList (country); //a new array for user to add data to
public static void main (String args [])throws IOException
{
// now i am adding data to the arrays
country[0] = "Barbados";
capital[0] = "Bridgetown";
population[0] = 65.3;
country[1] = "france";
capital[1] = "paris";
population[1] = 315.8;
country[2] = "nigeria";
capital[2] = "abuja";
population[2] = 170.1;
country[3] = "USA";
capital[3] = "washington";
population[3] = 2840;
country[4] = "japan";
capital[4] = "tokoyo";
population[4] = 126.7;
int option = 0;
System.out.println("WELCOME TO MY COUNTRY DATABASE\n");
while(option!= 5){ //Only five options
options();
option = Integer.parseInt(br.readLine());
if(option > 5 || option < 1)
{
System.out.println("Wrong input! Try Again");
System.out.println("CHOOSE FROM 1 - 5 \n ");
}
if(option == 1) {
addCountry();
}
else if(option == 2){
searchCountry(); //Search from an array
}
else if(option == 3){
ListCountry();
}
else if(option == 4){
getFare(); //show fare to travel
}
else if(option == 5) {
System.out.print("\n Thank you and Goodbye ");
}
}
}
public static void options()
{
System.out.println("Main menu");
System.out.println("=========");
System.out.println("1. Add a new country");
System.out.println("2. Search for a country");
System.out.println("3. Show list of countries available");
System.out.println("4. Get fare from London to countries listed");
System.out.println("5. Exit");
System.out.print("\n Choose an option from 1 - 5: ");
}
public static void addCountry()throws IOException
{
System.out.println("\n Adding a country");
System.out.println("===================");
System.out.print("Enter name of country: ");
String countryInput = br.readLine();
System.out.print("Enter Capital: ");
String capitalInput = br.readLine();
System.out.print("Enter population: ");
String populationInput = br.readLine();
int spareSlot = -1;
for (int i = 0; i < country.length; i++) // loop so data can be added to arraylist
{
if(country[i] == null)
{
spareSlot = i;
break;
}
}
country[spareSlot] = countryInput;
capital[spareSlot] = capitalInput;
population[spareSlot] = Double.parseDouble(populationInput);
System.out.println("\n You added the country " + countryInput + ", the capital is " + capitalInput + ", with a population of " + populationInput + "\n" );
//System.out.println("================================================================================================================");
}
public static void searchCountry() throws IOException
{
Scanner in = new Scanner (System.in);//Scanner to obtain input from command window
String output;
int size, i;
System.out.println("\n Searching countries");
System.out.println("========================= \n");
System.out.print("Search a Country: ");
output = br.readLine();
boolean found = false;
//A loop to search from the array
for(i = 0; i < country.length; i++)
if(output.equals(country[i]))
{
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i +"\n");
else
System.out.println(output + ": This country is not found, choose option 1 to Add country \n");
if (output == country[0])
{
System.out.println("The capital of "+ output + "is " + capital[1] + " with a population of " + population[3]);
}
if(output == country[1]) {
System.out.println("The capital is" + capital[4]);
}
if(output == country[2]) {
System.out.println("The capital is" + capital[1]);
}
if(output == country[3]) {
System.out.println("The capital is " + capital[2]);
}
if(output == country[4]) {
System.out.println("The capital is " + capital[3]);
}
}
public static void ListCountry()throws IOException
{
for (String c : countriesList)
{
if(c!=null)
System.out.println("\n" + c +"\n"); // to list all countries so far in the array
}
}
public static void getFare()
{
Scanner input = new Scanner (System.in);
String destination;
int fare;
System.out.println("\n Get a fare:");
System.out.println("============== \n");
System.out.print("Select destination by entering number from 1 -5: \n");
System.out.println("1 Caribbean");
System.out.println("2 Europe");
System.out.println("3 Africa");
System.out.println("4 America");
System.out.println("5 Japan");
destination = input.nextLine(); //get destination from user
fare = Integer.parseInt(destination);
switch(fare)
{
case 1: System.out.println("To travel to the Carribbean the fare is from £600 \n");
break;
case 2: System.out.println("To travel to Europe the fare is from £199 \n");
break;
case 3: System.out.println("To travel to Africa the fareis from £500 \n");
break;
case 4: System.out.println("To travel to America the fare is from £290 \n");
break;
case 5: System.out.println("To travel to Japan the fare is from £550 \n");
break;
default: System.out.println("INVALID ACTION START AGAIN \n");
System.out.println("======================================");
}
}
}

You have one comparison reading
if(output.equals(country[i]))
If you want this to be case-insensitive, you want to change that to
if(output.equalsIgnoreCase(country[i]))
Later in your code, you have lines similar to
if (output == country[0])
which compares object identity rather than string equality. You want to change all these to at least properly compare strings, and possibly to be case-insensitive as above.

Related

Error: Could not find or load main class Disneyland

My code compiles and I have two text files that need to be read from the program but when I run the program I get the following error: the menuItems.txt contains:
Churro
Ice Cream
Hamburger
Cheese burger
Turkey Leg
Corn Dog
Pizza
Funnel Cake
Soda
The priceItems contains:
5
4
9
10
13
7
9
6
5
All Files are located on my desktop
Error: Could not find or load main class Disneyland
package com.Kassie$;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Disneyland {
//Initialize the items 1D array
public static String[] getItems() {
try {
//Read from file
String[] aItems = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuItems.txt")))
.split("\n");
return aItems;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Initialize the items 1D array
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Find the character's location
public static String findLocation(String[][] storedValue, String name) {
for(int i = 0; i < storedValue.length; i++) {
if(storedValue[i][0].equals(name)) {
return (storedValue[i][1]);
}
}
return null;
}
public static void main(String[] args) {
char choice = ' ';
int totPrice = 0;
Scanner s = new Scanner(System.in);
String[][] characterLocation = {{"Mickey Mouse","Main Street USA"},
{"Minnie Mouse", "Toon Town"},
{"Goofy","Frontier Land"},
{"Pluto","Tomorrowland"},
{"Belle","Fantasyland"},
{"Jasmine", "Adventureland"}};
System.out.println("Do you like to know the "
+ "Disney Character's location(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Enter the name of the character");
String aName = s.next();
String location = findLocation(characterLocation,aName);
if( location != null) {
System.out.println("The character is located in " + location);
}
else {
System.out.println("Sorry! The character you are looking for "
+ "is not in park today");
}
}
String[] items = getItems();
String[] prices = getPrices();
choice = ' ';
System.out.println("Would you like to view the menu?(Y/N)");
choice = s.next().charAt(0);
if(choice == 'N' || choice == 'n') {
System.exit(0);
}
while(choice == 'Y' || choice == 'y') {
for(int i = 0; i < items.length; i++) {
System.out.println("Enter " + (i+1) + " for " + items[i]);
}
int option = s.nextInt();
System.out.println("Item : " + items[option-1]);
System.out.println("Price : " + prices[option-1]);
totPrice = totPrice + Integer.parseInt(prices[option-1]);
System.out.println("Do you want to order more(Y/N)?");
choice = s.next().charAt(0);
}
System.out.println("Are you an Annual Pass Holder?(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Your bill amount due : $" + ((double)totPrice -
((double)(totPrice*15))/100));
System.exit(1);
}
System.out.println("Your bill amount due : $" + totPrice);
}
}
You need to escape the dollar sign in your path.
To match a dollar sign, use "\$"
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie\\$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

Unsure of where to add certain piece of code

I have written some code which allows me to get user input for games a user has played. I have done most of it, however I have come to a point where I do not know where to add this code totalScore = totalScore + score;. This code will get me the total score of the player each time they add a new game. As well as this I am also confused about how to get a total amount of invalid entries which a user has tried to enter, meaning for each invalid entry I need to keep count of it so I can later display the total amount of invalid entries.
import java.util.Scanner;
public class REQ3
{
public static void main (String[] args)
{
String playername;
String line;
String[] list = new String[100];
int count = 0;
int score;
int time;
int gamesplayed =0;
int totalScore =0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
playername = sc.nextLine();
if(playername.equals(""))
{
System.out.println("Player name was not entered please try again");
System.exit(0);
}
System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");
while (count < 100){
line = sc.nextLine();
if(line.equals("quit")){
break;
}
if(line.equals("")){
System.out.println("Nothing was entered please try again");
break;
}
if(!(line.contains(":"))){
System.out.println("Please enter achivements with the proper \":\" sepration\n");
break;
}
list[count]=line;
System.out.println("list[count]" + list[count]);
count++;
gamesplayed++;
for (int i=0; i<count; i++){
line=list[i];
String[] elements =line.split(":");
if (elements.length !=3){
System.out.println("Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
break;
}
try {
score = Integer.parseInt(elements[1].trim());
totalScore = totalScore + score; // added here
} catch(NumberFormatException ex) {
System.out.println("Incorrect score data, Please enter a valid integer");
}
try {
time=Integer.parseInt(elements[2].trim());
} catch(NumberFormatException ex) {
System.out.println("Incorrect time data, Please enter a valid integer");
}
}
}
System.out.println("Player : " + playername);
System.out.println("--------------------------------");
System.out.println("Games Played: " +gamesplayed);
}
}
I dont know why you are using a for loop . You should remove the for loop and do totalScore after reading score
import java.util.Scanner;
public class REQ3 {
public static void main(String[] args) {
String playername;
String line;
String[] list = new String[100];
int count = 0;
int time;
int gamesplayed = 0;
int totalScore = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
playername = sc.nextLine();
if (playername.equals("")) {
System.out.println("Player name was not entered please try again");
System.exit(0);
}
System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");
while (count < 100) {
line = sc.nextLine();
if (line.equals("quit")) {
break;
}
if (line.equals("")) {
System.out.println("Nothing was entered please try again");
break;
}
if (!(line.contains(":"))) {
System.out.println("Please enter achivements with the proper \":\" sepration\n");
break;
}
list[count] = line;
System.out.println("list[count]" + list[count]);
count++;
gamesplayed++;
String[] elements = line.split(":");
if (elements.length != 3) {
System.out.println(
"Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
break;
}
try {
int score = Integer.parseInt(elements[1].trim());
totalScore += score;
} catch (NumberFormatException ex) {
System.out.println("Incorrect score data, Please enter a valid integer");
}
try {
time = Integer.parseInt(elements[2].trim());
} catch (NumberFormatException ex) {
System.out.println("Incorrect time data, Please enter a valid integer");
}
}
System.out.println("Player : " + playername);
System.out.println("--------------------------------");
System.out.println("Games Played: " + gamesplayed);
System.out.println("total score: " + totalScore);
}
}
Agree with awesome not sure why you need inner for loop. Below is the solution which work for both invalid entries and total score.
import java.util.Scanner;
public class REQ3 {
public static void main(String[] args) {
String playername;
String line;
String[] list = new String[100];
int count = 0;
int score = 0;
int time;
int gamesplayed = 0;
int totalScore = 0;
int invalidEntries = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
playername = sc.nextLine();
if (playername.equals("")) {
System.out.println("Player name was not entered please try again");
System.exit(0);
}
System.out
.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");
while (count < 100) {
line = sc.nextLine();
if (line.equals("quit")) {
break;
}
if (line.equals("")) {
System.out.println("Nothing was entered please try again");
invalidEntries++;
continue;
}
if (!(line.contains(":"))) {
System.out
.println("Please enter achivements with the proper \":\" sepration\n");
invalidEntries++;
continue;
}
list[count] = line;
System.out.println("list[count]" + list[count]);
String[] elements = line.split(":");
if (elements.length != 3) {
System.out
.println("Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
invalidEntries++;
continue;
}
try {
score = Integer.parseInt(elements[1].trim());
} catch (NumberFormatException ex) {
System.out
.println("Incorrect score data, Please enter a valid integer");
invalidEntries++;
continue;
}
try {
time = Integer.parseInt(elements[2].trim());
} catch (NumberFormatException ex) {
System.out
.println("Incorrect time data, Please enter a valid integer");
invalidEntries++;
continue;
}
count++;
gamesplayed++;
totalScore = totalScore + score;
}
System.out.println("Player : " + playername);
System.out.println("--------------------------------");
System.out.println("Games Played: " + gamesplayed);
System.out.println("Total Score: " + totalScore);
System.out.println("Invalid Entries: " + invalidEntries);
}
}

Scanner ignoring the String "name"

I am trying to take user input for name, last name, phone number and age.
For some odd reason the scanner is skipping name but none of the other variables.
Can someone point out my mistake please? I can't figure it out.
import java.util.Scanner;
public class Lab2{
String [][] info = new String [10][4];
public static void main(String [] args){
new Lab2();
}
public Lab2(){
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println("Student contact Interface");
System.out.println("Please select a number from the options below:");
while(true){
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("3: Display the contact list.");
System.out.println("0: Exit the contact list.");
int options = input.nextInt();
String name, lastName, number, age;
switch(options){
case 1:
System.out.println("Please enter the name: ");
name = input.nextLine(); // This is the String var that is not accepting input from...
System.out.println("Please enter the last name: ");
lastName = input.nextLine();
System.out.println("Please enter the phone number: ");
number = input.nextLine();
System.out.println("Please enter the age (eg. 25): ");
age = input.nextLine();
addStudent(name, lastName, number, age);
break;
case 2:
System.out.println("\nEnter the name to remove: ");
String delName = input.nextLine();
System.out.println("\nEnter the last name to remove: ");
String delLastName = input.nextLine();
remove(delName, delLastName);
break;
case 3:
display();
break;
case 0:
System.out.println("Thank you for using the contact Database.");
System.exit(0);
}
}
}
public void addStudent (String name, String lastName, String number, String age){
boolean infoInserted = false;
for(int i = 0; i < 10; i++){
if(info[i][0] == null || info[i][0].equals(null)){
info[i][0] = name;
info[i][1] = lastName;
info[i][2] = number;
info[i][3] = age;
infoInserted = true;
break;
}
}
if(infoInserted){
System.out.println("\nContact saved.\n");
}
else{
System.out.println("\nYour database is full.\n");
}
}
public void remove(String delName, String delLastName){
boolean removed = false;
int i = 0;
for (i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
if (info[i][0].equals(delName) && info[i][1].equals(delLastName)) {
while (i < 9) {
info[i][0] = info[i + 1][0];
info[i][1] = info[i + 1][1];
info[i][2] = info[i + 1][2];
info[i][3] = info[i + 1][3];
i++;
}
info[9][0] = null;
info[9][1] = null;
info[9][2] = null;
info[9][3] = null;
removed = true;
break;
}
}
}
if (removed) {
System.out.println("Contact removed.");
}
else {
System.out.println("Contact was not found.");
}
}
public void display (){
for (int i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
System.out.println("Contact " + (i + 1)+ ":");
System.out.println("\t" + info[i][0]);
System.out.println("\t" + info[i][1]);
System.out.println("\tPhone Number:" + info[i][2]);
System.out.println("\tAge:" + info[i][3]);
}
}
}
}
Add a
input.nextLine();
after your
int options = input.nextInt();
This is because:
nextInt method does not read the last newline character (of your integer input)
that newline is consumed in the next call to nextLine
causing name 'to be skipped'
so you need to 'flush away' the newline character after getting the integer input
Another option:
Take in the entire line, using input.nextLine()
Get the integer value using Integer.parseInt() to extract the integer value
It is skipping name because , input.nextInt() wont go to next input line.
You can use
int option=Integer.parseInt(input.nextLine());
then it wont skip name.

Trying to make a program, but struggling with delete option

if I choose option 3 on this program, I would like it to delete one of the exam grades.
The program outputs like this at the moment if option 2 (view grades) is chosen:
1) Bob Jones, Comp, 18
2) Matt Jones, computing, 100
3) Adam Frank-Jones, Drama, 69
As you can see in the code, the numbers incrementing down the side are represented by "i". What I'm looking for is if I enter "1" for example when choosing a row to delete, it deletes a row (in this case "1) Bob Jones, Comp, 18"). A row is made up of i + First Name + Surname + Course + Mark, all concatenated together.
Now, I have looked around the internet on code helping me do delete an entry. I have tried if i equals user input, then delete. I have tried using a temporary file where the user searches by first name (I am unsure how to code this though") and then writes back to original using BufferedWriter etc. I have been unsuccessful on making this work though.
Can anyone help me? Thanks
Code:
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class ExamGrades {
public static void main(String[] args) throws Exception {
BufferedReader reader = null;
FileWriter grades = new FileWriter("grades2.txt",true);
BufferedWriter bw = new BufferedWriter(grades);
PrintWriter out = new PrintWriter(bw);
Scanner scan = new Scanner(System.in);
int examMark = 0;
String firstName = "";
String surName = "";
String course = "";
String entry = "";
String firstCap = "";
String surCap = "";
int menu =0;
System.out.println("Welcome to the 'GradeEnter' program! ");
System.out.println("Menu: ");
System.out.println("1) Enter Student Grade(s)");
System.out.println("2) View Student Grade(s)");
System.out.println("3) Delete Grade(s)");
System.out.println("4) Exit");
menu = scan.nextInt();
switch (menu) {
case 1:
System.out.print("Please enter student first name: ");
firstName = scan.next();
while(!firstName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid first name: ");
firstName = scan.next();
}
firstCap = firstName.substring(0,1).toUpperCase() + firstName.substring(1);
System.out.print("Please enter student surname: ");
surName = scan.next();
while(!surName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid surname: ");
surName = scan.next();
}
surCap = surName.substring(0,1).toUpperCase() + surName.substring(1);
System.out.print("Please select student course: ");
course = scan.next();
System.out.print("Please enter student mark: ");
while (!scan.hasNextInt())
{
System.out.print("Please enter a valid mark: ");
scan.next();
}
examMark = scan.nextInt();
if (examMark < 40)
{
System.out.println("Failed");
}
else if (examMark >= 40 && examMark <= 49)
{
System.out.println("3rd");
}
else if (examMark >= 50 && examMark <= 59)
{
System.out.println("2/2");
}
else if (examMark >= 60 && examMark <= 69)
{
System.out.println("2/1");
}
else if (examMark >= 70 && examMark <= 100)
{
System.out.println("1st");
}
else
{
System.out.println("Invalid Mark");
}
entry = (firstCap + " " + surCap + ", " + course + ", " + examMark);
out.println(entry);
break;
case 2:
File file = new File("grades2.txt");
reader = new BufferedReader(new FileReader(file));
int i =1;
String line;
while ((line = reader.readLine()) != null) {
System.out.println(i + ") " + line);
i++;
}
break;
case 3:
// HERE
break;
case 4:
System.out.println("Thanks for using 'GradeEnter' ");
System.exit(0);
break;
}
out.close();
scan.close();
}
}

Very simple game about Guessing The Number

/hello, I am trying to learn how to use "break" commend in java as well as continuing loop with "y or n" choice. I am writing this game Guessing Number and I have some trouble with "y" choice. I will try to explain, to write a game of guessing number was easy so I started to add some conditions like the possibility on the and to play again or not, later I was thinking that would be more interesting if I add possibility to quit any time player wish, but that does not working correctly. Please help, thats my code
package guessinggame;
import java.util.Random;
import java.util.Scanner;
/**
*
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
}
}
Here is an alternative that achieves that same outcome
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
int guess = 0;
int number_of_tries = 0;
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
guess = input.nextInt(); //get first input
while (guess != -1)
{
int number_guess = rand.nextInt(5) + 1;
++number_of_tries;
//check if user wins and exits loop
if (isWin (number_guess,guess))
{
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? [1 yes/ -1 no]: ");
guess = input.nextInt();
if (guess == -1)
break;
else
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
}
else if (number_guess < guess )
{
System.out.println(" Guess is too High " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
else if (number_guess > guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
}
System.out.println ("bye bye");
}
public static boolean isWin (int number,int guess)
{
return (number == guess) ? true :false;
}
}
You forgot to wait for user input after this statement:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
E.g. you could try next approach:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (input.hasNext()) {
if (another.equalsIgnoreCase("y")) {
play_again = true;
input.next();
} else {
play_again = false;
}
}
It looks like your braces are messed up for your play again if statement
This will work.
package aa;
import java.util.Random;
import java.util.Scanner;
public class abc {
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
break;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
input.next();
if (win == true){
System.out.println(" You Win!!! ");
}
else{
System.out.println(" Good Luck Next Time!!! ");
System.out.println(" The number was " + number_guess);
}
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
another = input.next();
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
System.out.println("Thank you!!!");
}
}

Categories

Resources