Unsure of where to add certain piece of code - java

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

Related

How to end this program when user inputs "end"?

So basically I am trying to figure out how to stop this program using Integer.valueOf(String s) or Integer.parseInt(String s) by typing "end" for the user input
import java.util.Scanner;
public class monkey1{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int sum = 0;
int lol = 1;
do {
System.out.print("Enter a number: ");
lol = s.nextInt();
sum += lol;
if (lol > 0) {
System.out.println("Sum is now: " + sum);
}
} while (lol>0);
}
}
First - you need to change lol=sc.nextInt() to String tmp = s.nextLine()
Second - do
try {
if (tmp.equals("END")) {
break; // This will exit do-while loop
}
lol = Integer.parseInt(tmp);
} catch (NumberFormatException e) {
e.printStackTrace();
// Here you can also exit loop by adding break. Or just ask user to enter new text.
}
you should learn how to use try/catch.
Here we go:
String text = "";
int lol = 1;
do {
System.out.print("Enter a number: ");
text = s.nextLine();
try {
lol = Integer.valueOf(text);
}catch (Exception e){
System.out.println("Exit");
System.exit(0);
}
Here is your code
package Phone;
import java.util.Scanner;
public class monkey1{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int sum = 0;
int hi = 1;
do {
System.out.print("Enter a number: ");
String lol = s.nextLine();
if(lol.equals("end")) {
break;
}
hi = Integer.parseInt(lol);
sum += hi;
if (hi > 0) {
System.out.println("Sum is now: " + sum);
}
} while (hi > 0);
}
What I did here is I changed lol to hi for adding and took String input so that you can input end...
I would suggest checking if s.equals("end") before converting to int so something like this:
do {
System.out.print("Enter a number: ");
String userValue = s.nextLine();
if(userValue.equals("end")
break;
lol = Integer.parseInt(userValue);
sum += lol;
if (lol > 0){
System.out.println("Sum is now: " + sum);
}
}while (lol>0);

Cant get my integers to add to get correct output

so I am trying to do my homework, this being the question:
Write a program that prompts the user to read two integers and displays their sum. If anything but an integer is passed as input, your program should catch the InputMismatchException that is thrown and prompt the user to input another number by printing "Please enter an integer."
Below is the sample run and what I am supposed to test.
SAMPLE RUN #1: java InputMismatch
Enter an integer: 2.5↵
Please enter an integer↵
Enter an integer: 4.6↵
Please enter an integer↵
Enter an integer: hello!↵
Please enter an integer↵
Enter an integer:7↵
Enter an integer:5.6↵
Please enter an integer↵
Enter an integer:9.4↵
Please enter an integer ↵
Enter an integer:10↵
17↵
When I am testing my code and putting in the integers, it works as it is supposed to, however, I am stuck on getting the integers to add together when both inputs are entered correctly. What am I doing wrong?
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
try adding another condition to your while and putting the numbers in an array.
int[] numbers = new int[2];
and change this in your while loop:
int count = 0;
while (!isValid && count <2) {
try {
System.out.print("Enter an integer: ");
numbers[count] = input.nextInt();
count++;
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
Hope that helped.
Check with this approach:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
numArray[count] = number;
count++;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
int num1 = numArray[0];
int num2 = numArray[1];
System.out.println((num1 + num2));
}
You need to stitch together the logic. As you are taking 2 numbers 2 flags will ensure you got correct input for both variables. Also both flags ensure you are taking input correctly for num1 or num2 when an exception occurs.
If you need to input n arbitrary integers, then you may want to use dynamic collections and add numbers to collection.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean num1Valid = false;
boolean num2Valid = false;
while (num1Valid==false || num2Valid==false) {
try {
if(num1Valid == false) {
System.out.print("Enter an integer for num1: ");
num1 = input.nextInt();
System.out.println("The number entered for num1 is " + num1);
num1Valid = true;
}
if(num2Valid == false) {
System.out.print("Enter an integer for num2: ");
num2 = input.nextInt();
System.out.println("The number entered for num2 is " + num2);
num2Valid = true;
}
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
input.close()
System.out.println((num1 + num2));
}
You need capture the exception, in this case you can using e.getMessage()
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1=0, number=0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
number = input.nextInt();
if(number > 0) {
System.out.println("The number entered is " + number);
}
num1 += number;
System.out.println("are would you like continue the program? Y or
N ");
String condition = input.next();
if(condition.equalsIgnoreCase("Y")) {
isValid = false;
} else {
isValid = true;
}
}
catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
System.out.println("You cannot type words");
isValid = true;
}
}
System.out.println("Result = " + num1);
input.close();
}
}
in another case do you can use the method matches using expression language
saw example below:
if(valor.matches("[0-9]*"))
You can add the two numbers inside the try block
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
num1 = input.nextInt();
System.out.print("Enter an integer: ");
num2 = input.nextInt();
System.out.println("The numbers you entered are " + num1 + ","+num2);
int sum = num1+num2;
System.out.println("The sum Of the numbers you entered is: "+ sum);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer:");
int number = input.nextInt();
numArray[count] = number;
count++;
} catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
input.nextLine();
}
}
System.out.println(numArray[0] + numArray[1]);
}
}

redirect a loop within a loop for only "else"

I'm a total beginner and am working on a practice assignment. I need to be able to re-print the same addition problem if the user has answered incorrectly, but I'm not sure how to do that. All my attempts have lead to a new random addition problem appearing or adding another new random to the original, which is also not desired. I'm sure it's simple, but I am lost. Thanks in advance for any tips!
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do {
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b)) {
System.out.println("CORRECT!");
} else if (ans==0) {
System.out.println("Good bye!");
} else if (ans!=(a+b)) {
System.out.println("Incorrect, try again.");
}
} while (ans!=0);
}
}
Just simplify your code a little bit, don't overthink. You generate answers every time you get into the loop, generate your numbers outside so they stay consistent, also, a do-while, isn't necessary, just break your loop if the answer is correct or they placed 0. Also, you need to make sure that the user entered a number, so a try-catch should be placed while getting the input.
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
int ans;
while (true) {
System.out.printf("%d + %d = ?%n", a, b);
try {
ans = Integer.parseInt(input.next());
} catch (NumberFormatException e) {
System.out.println("Please enter a number!");
continue;
}
if (ans == 0) {
System.out.println("Goodbye!");
break;
} else if (ans == a + b) {
System.out.println("Correct!");
break;
} else {
System.out.println("Incorrect!");
}
}
Please see modification inline:
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
// here you keep asking the user over and over
//until they give the right result
do{
System.out.println("Incorrect, try again.");
//show again the equation to the user
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
}while(ans!=(a+b));
}
}
while (ans!=0);
}
}
Use this simple source code and similar to you (minor change):
try (Scanner input = new Scanner(System.in)) {
Random rand = new Random();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans, a, b;
ans = a = b = 0;
do {
a = rand.nextInt(10) + 1;
b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b + " = ");
try{
//Getting input as String and casting to Integer
ans = Integer.parseInt(input.nextLine());
if (ans == 0) {
System.out.println("Good bye!");
} else if (ans == (a + b)) {
System.out.println("CORRECT!");
} else if (ans != (a + b)) {
System.out.println("Incorrect, try again.");
}
}catch (NumberFormatException nfe){
System.out.println(nfe);
}
} while (ans != 0);
}
class generateNum{
Random rand = new Random ();
int a=rand.nextInt(10)+1;
int b=rand.nextInt(10)+1;
public void generate(){
System.out.print(a + " + " + b +" = ");
}
public int getsum(){
return a+b;
}
}
public class Test02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
generateNum gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
int com=gnum.getsum();
do
{
if (ans==com)
{
System.out.println("CORRECT!");
gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
com=gnum.getsum();
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=com)
{
System.out.println("Incorrect, try again.");
gnum.generate();
ans = input.nextInt();
}
}
while (ans!=0);
}
}
There are few changes in your condition. Update your else-if(ans!=(a+b)) block.
import java.util.Random;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
boolean flag = false;
do{
System.out.println("Incorrect, try again.(0 for skip)");
int againAns = input.nextInt();
if(againAns == (a+b)){
System.out.println("CORRECT!");
flag = true;
}else if(againAns == 0){
System.out.println("You skip the answer..");
flag = true;
}
}while(flag != true);
}
}while (ans!=0);
}
}

How to Subtract n numbers using for loop in java?

When I use for loop for subtraction, i don't get a correct output.
What logic should i apply in my code to get my subtraction correctly using for loop?
Please help me as i am new in JAVA.
My code is as Follow:
import java.io.*;
import java.util.*;
class Sub
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int a,n,i;
String yn;
boolean loop=true;
while(loop)
{
try
{
do
{
loop=true;
System.out.println("Enter how many numbers to Subtract?: ");
n=s.nextInt();
int sum=0;
for(i=1;i<=n;)
{
try
{
System.out.println("Enter number "+i+" : ");
a=s.nextInt();
sum=a-sum;
i++;
}
catch(Exception e)
{
System.out.println("Invalid Entry. Try again!!");
}
}
System.out.println("Answer is:"+sum);
System.out.println("Do you want to continue?(Y/N): ");
yn=s.next();
loop=yn.equals("Y")||yn.equals("y");
}while(loop);
}
catch(Exception e)
{
System.out.println("Re-enter the Limit");
}
}
}
}
You should start with sum as the first number (not zero) and subtract the rest of the numbers from it:
loop=true;
System.out.println("Enter how many numbers to Subtract?");
n=s.nextInt();
int sum=0;
for(i=1;i<=n;)
{
try
{
System.out.println("Enter number "+i+" : ");
a=s.nextInt();
sum=a-sum;
i++;
}
catch(Exception e)
{
System.out.println("Invalid Entry. Try again!!");
}
}
to:
...
loop = true;
System.out.println("Enter how many numbers to Subtract?: ");
n = s.nextInt();
System.out.println("Enter number 1 : ");
int sum = s.nextInt();
for (int i=2; i <= n; i++) {
try {
System.out.println("Enter number " + i + " : ");
a = s.nextInt();
sum -= a;
} catch (Exception e) {
System.out.println("Invalid Entry. Try again!!");
}
}
...
Further, instead of doing:
yn.equals("Y") || yn.equals("y")
you can use equalsIgnoreCase():
yn.equalsIgnoreCase("Y")
And last, you should use meaningful names for variables (it's recommended to develop good habits even if it's such a small program), so instead of:
int a, n, i; // you can define and use i inside the for-loop - no need to define it outside
String yn;
consider using more expressive names, such as:
int inputNumber, numberOfVariables;
String continueLooping;
The following version could be improved (refactored even further):
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
int numOfArguments = getNumberOfArguments(scanner);
int sum = getNextNumberFromUser(scanner, 1);
for (int i = 2; i <= numOfArguments; i++) {
sum -= getNextNumberFromUser(scanner, i);
}
System.out.println("Answer is: " + sum + "\n\nDo you want to continue?(Y/N): ");
String runAgain = scanner.next();
if (runAgain.equalsIgnoreCase("N")) {
break;
}
}
}
private static int getNextNumberFromUser(Scanner scanner, int i) {
while (true) {
try {
System.out.println("Enter number " + i + " : ");
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid Entry. Try again!!");
scanner.nextLine();
}
}
}
private static int getNumberOfArguments(Scanner scanner) {
int numberOfArguments = -1;
System.out.println("Enter how many numbers to Subtract?: ");
while (numberOfArguments == -1) {
try {
numberOfArguments = scanner.nextInt();
if (numberOfArguments <= 0) {
numberOfArguments = -1;
}
} catch (InputMismatchException e) {
System.out.println("Illegal number of arguments to subtract, please try again: ");
scanner.nextLine();
}
}
return numberOfArguments;
}

how to recognise capital letters and not just lower case

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.

Categories

Resources