I just want to print the String "code", which the user enters in the method, but it is printing "null", but when i want to print int num, it prints what the user enters. The output should print all the details that the user entered; sort of like an ID thing. This should be very simple but for some reason I am not able to do it and Im starting to lose hope. Any help would be appreciated. Thanks
public class Lab2 {
static String code;
static String num;
int year;
static int sem;
public static void main(String[] args) {
info();
num();
sem();
System.out.println(num + " " + sem + " " + code);
}
public static void info() {
Scanner sc = new Scanner(System.in);
System.out.println("Course ID Generator\n--------------------------");
System.out.println("Please Enter Course Information:");
String message = "Initial";
String code = "";
while (!message.isEmpty()) {
if (!message.equals("Initial")) {
System.out.println(message);
}
System.out.print("Course Code (only capital letters " + "with a length between 2 and 4): ");
code = sc.nextLine();
message = checkLength(code);
if (message.isEmpty()) {
message = checkUpperCase(code);
}
}
}
private static String checkLength(String code) {
String output = "";
if (code.length() < 2 || code.length() > 4) {
output = "Course Code length was not between " + "2 and 4, Please try again";
}
return output;
}
private static String checkUpperCase(String code) {
String output = "";
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) && Character.isUpperCase(ch)) {
} else {
output = "Course Code must only have capital " + "letters, please try again";
break;
}
}
return output;
}
public static void num() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Course Number (consists of only 3 digits): ");
num = sc.nextLine();
if (num.length() == 3) {
break;
} else {
System.out.println("Course Number length was not 3, please try again");
}
sc.close();
}
}
public static void sem() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Semester (Fall=01, Sprint=02, Summer=03):");
sem = sc.nextInt();
if (sem > 0 && sem < 4) {
break;
} else {
System.out.println("Please enter correct semester code, try again");
}
}
sc.close();
}
}
Remove the line
String code = "";
in your info Method
You are using the same variable code twice.
Read this for further information https://dzone.com/articles/variable-shadowing-and-hiding-in-java
Related
I was working on a Uni project for the end of the semester. The program is a simple bank system. My issue is that when the program first launches it creates a "Log" folder. Then when an account object is created using a Constructor a new txt file is created in the folder with the name of the account holder. Up until here I have managed to do it.
The issue is that when closing the program via the option menu but before closing the program, all the details from all the created objects (which are stored in a array) are written in their respective files following the order they are stored in the object array but on the first run the files are created but nothing is written in them.
Then on the 2nd run if I close the program again the details are written correctly. Can I have some suggestions please I could not find anything regarding this online?
import java.util.Scanner;
import java.io.*;
public class FileManagement {
static String pathnameFile = "src\\Log";
static File directory = new File(pathnameFile);
static String[] allFiles = directory.list();
public static void createFolder() {
File logFile = new File(pathnameFile);
if (!logFile.exists()) {
logFile.mkdir();
}
}
public static void writeFiles() throws IOException {
FileWriter writer;
for (int i = 0; i < allFiles.length; i++) {
writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
writer.close();
}
}
//original method
/*public static void readFiles() {
Scanner reader;
for (int i = 0; i < allFiles.length; i++) {
reader = new Scanner(pathnameFile + allFiles[i]);
}
}*/
//My solution
public static void readFiles() throws IOException{
if(directory.exists() == false || allFiles == null) {
return;
}
Scanner reader;
File currentFile;
String[] data = new String[4];
for(int i = 0; i < allFiles.length; i++) {
currentFile = new File(pathnameFile + "\\" +allFiles[i]);
reader = new Scanner(currentFile);
int count = 0;
while(reader.hasNextLine()) {
if(!reader.hasNext()) {
break;
}
reader.next();
data[count] = reader.next();
count++;
}
reader.close();
String accountName = data[0];
String PIN = data[1];
int balance = Integer.parseInt(data[2]);
eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
}
}
}
import java.util.Scanner;
import java.io.*;
public class App {
public static eBanking currentAccount;
public static void mainMenu() throws Exception{
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("""
--------------------------------------------------------
1. Log in
2. Register
0. Exit.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
System.out.println("Please enter your account name and PIN below.");
System.out.print("Account name: ");
String accountName = input.next();
System.out.print("PIN: ");
String PIN = input.next();
System.out.println();
for (int i = 0; i < eBanking.accounts.length; i++) {
if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
eBanking.accounts[i].welcome();
currentAccount = eBanking.accounts[i];
break;
}
}
menu();
}
case 2 -> {
System.out.println("Please enter the account name, PIN and inital balance of your new account.");
System.out.print("Account name:");
String accountNameRegister = input.next();
System.out.print("PIN: ");
String registerPIN = input.next();
System.out.print("Initial balance: ");
int initialBalance = input.nextInt();
currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
menu();
}
default -> {
FileManagement.writeFiles();
System.exit(0);
}
}
}
}
public static void menu() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("""
--------------------------------------------------------
1. Show your balance.
2. Withdraw money.
3. Deposit money.
4. Change your PIN.
5. Transfer money to another person.
0. Back.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
currentAccount.showBalance();
}
case 2 -> {
System.out.println("Please enter the amount you want to withdraw: ");
int withdrawAmount = input.nextInt();
currentAccount.withdraw(withdrawAmount);
}
case 3 -> {
System.out.println("Please enter the amount you want to deposit: ");
int depositAmount = input.nextInt();
currentAccount.deposit(depositAmount);
}
case 4 -> {
currentAccount.changePIN();
}
case 5 -> {
System.out.println("Please enter the amount you want to send: ");
int amount = input.nextInt();
System.out.println("Please enter the account number you want to send the money to: ");
String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)
System.out.println("The amount of money is completed");
currentAccount.transfer(amount, transferAccount);
}
case 0 -> {
return;
}
default -> {
System.out.println("Please enter a number from the menu list!");
}
}
}
}
public static void main(String[] args) throws Exception {
FileManagement.createFolder();
FileManagement.readFiles();
mainMenu();
}
}
import java.util.Scanner;
import java.io.*;
public class eBanking extends BankAccount {
// Variable declaration
Scanner input = new Scanner(System.in);
private String accountName;
private String accountID;
public static eBanking[] accounts = new eBanking[100];
// Methods
public String getAccountName() {
return accountName;
}
public void welcome() {
System.out.println("---------------------------------------------------------------------------------------");
System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
}
public void transfer(int x, String str) {
boolean foundID = false;
withdraw(x);
if (initialBalance == 0) {
System.out.println("Transaction failed!");
} else if (initialBalance < x) {
for(int i = 0; i < numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += initialBalance;
System.out.println("Transaction completed!");
foundID = true;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += initialBalance;
return;
}
} else {
for(int i = 0; i <= numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += x;
System.out.println("Transaction completed!");
foundID=true;
return;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += x;
return;
}
}
}
// Constructors
public eBanking(String name){
int firstDigit = (int)(Math.random() * 10);
int secondDigit = (int)(Math.random() * 10);
int thirdDigit = (int)(Math.random() * 10);
int forthDigit = (int)(Math.random() * 10);
accountID = this.toString();
PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha
balance = 0; //dhe nuk duhet ta perseris per the gjitha
accountName = name;
accounts[numberOfAccount] = this;
numberOfAccount++;
System.out.println("---------------------------------------------------------------------------------------");
System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
}
public eBanking(String name, String pin, int x){
if (checkPIN(pin) == false) {
System.out.println("Incorrect PIN format!");
return;
}
accountID = this.toString();
accountName = name;
balance = x;
PIN = pin;
accounts[numberOfAccount] = this;
numberOfAccount++;
welcome();
}
}
import java.util.Scanner;
public abstract class BankAccount {
// Variable declaration
protected String PIN;
protected int balance;
public static int numberOfAccount = 0;
protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();
//Methods
//Balance
public int getBalance() {
return balance;
}
public void showBalance() {
System.out.println("The total balance of the account is " + balance);
}
public void withdraw(int x) {
initialBalance = balance;
if (balance == 0) {
System.out.println("The deduction has failed due to lack of balance!");
return;
}
if (balance < x) {
balance = 0;
System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
} else {
balance -= x;
System.out.println("The deduction of " + x + " from your balance is completed!");
}
}
public void deposit(int x) {
balance += x;
System.out.println("You have made a deposit of " + x + " and your current balance is " + balance);
}
//PIN
public String getPIN() {
return PIN;
}
public void changePIN() {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your previous PIN: ");
String tryPIN = input.nextLine();
if (tryPIN.equals(PIN)) {
System.out.print("Please enter your new PIN: ");
String newPIN = input.nextLine();
if (checkPIN(newPIN) == false) {
System.out.println("The PIN is not in the correct format!");
} else {
System.out.println("The PIN has been changed");
PIN = newPIN;
}
} else {
System.out.println("The PIN does not match!");
}
}
protected static boolean checkPIN(String str) {
boolean isValid;
if(str.length() != 4) {
isValid = false;
} else {
try {
int x = Integer.parseInt(str);
isValid = true;
} catch (NumberFormatException e) {
isValid = false;
}
}
return isValid;
}
//Kjo metode duhet per testim
public void getDetails() {
System.out.println(balance + " and PIN " + PIN);
}
}
I have updated the post showing how I fixed it and providing all my classes. Please do not mind the messy code as I am first trying it out with a switch and then will ditch that when the time comes and use GUI as soon as I learn how to use it. Also I know that the classes can be organized better but BankAccount and eBanking are 2 salvaged classes I used on a different exercise.
I think I have found a solution. I just remembered that when using FileWriter if a file does not exist it creates one automatically. So i have cancelled the method which creates a file whenever a new object is created and now whenever the program is closed the files are created if needed or overwritten if they already exist.
I have provided all the current code on my program and the fix I implemented on FileManagment class
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string:");
String name = sc.nextLine();
while(name.contains(",") == false) {
System.out.println("Error: No comma in string.");
System.out.println("Enter input string:");
name = sc.nextLine();
}
while(!name.equals("q") && !name.equalsIgnoreCase("q")) {
String[] splitting = name.split(",");
String first;
String second;
if(name.compareTo("q") == 1) {
break;
}
if(splitting[1].contains(" ")) {
first = splitting[0];
second = splitting[1].substring(splitting[1].indexOf(' ') + 1, splitting[1].length());
}
else {
first = splitting[0];
second = splitting[1];
}
System.out.println("First word: " + first);
System.out.println("Second word: " + second);
System.out.println("Enter input string:");
name = sc.nextLine();
while(name.contains(",") == false && name.equalsIgnoreCase("q")) {
System.out.println("Error: No comma in string.");
System.out.println("Enter input string:");
name = sc.nextLine();
}
}
System.out.println("Thank you!");
sc.close();
}
}
I'm trying to get this to work when the user inputs a q and it stops the while loop and says thank you at the end.
I have tried so many different ways to do this already.
sometimes it is simpler to break out of an endless loop:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter input string (q to quit):");
String input = sc.nextLine();
if ("q".equals(input.toLowerCase())) {
break;
} else if (input.contains(",")) {
String[] splitting = input.split(",");
String first;
String second;
if (splitting[1].contains(" ")) {
first = splitting[0];
second = splitting[1].substring(
splitting[1].indexOf(' ') + 1,
splitting[1].length());
} else {
first = splitting[0];
second = splitting[1];
}
System.out.println("First word: " + first);
System.out.println("Second word: " + second);
}
}
System.out.println("Thank you!");
sc.close();
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm creating a program that presents a menu to the user with four choices, namely entering a string, displaying it with spaces removed, displaying it backward, and quitting. How can I pass the string input from the EnterString method to the NoSpaces method and DisplayBackward method?
I tried follows:
public class StringMenu
{
public static String stringinput;
public static String s;
public String EnterString() {
System.out.print("Input a string: ");
Scanner newstring = new Scanner(System.in);
String stringinput = newstring.nextLine();
return stringinput;
}
public void setstring(String stringinput){
this.stringinput = stringinput;
}
public static void editString(String s){
s.setstring(stringinput);
}
public String NoSpaces() {
String stringinput2 = " ";
editString(stringinput2);
String enterfirst = "Enter a string first";
if(stringinput2 != null){
char[] Array = stringinput2.toCharArray();
String nospaces = "";
for (int n=0; n<Array.length; n++ )
{
if ((Array[n] != ' ') && (Array[n] != '\t'))
nospaces = nospaces + Array[n];
}
System.out.println(nospaces);
return nospaces;
}
else
System.out.println("Enter a string first");
return enterfirst;
}
public void DisplayBackward() {
String stringinput3 = " ";
editString(stringinput3);
if(stringinput3 != null) {
char[] orig = stringinput3.toCharArray();
String reverse="";
int p = orig.length-1;
for (int n=0; n<=p; p-- )
reverse = reverse + orig[p];
System.out.println(reverse);
}
else
System.out.println("Enter a string first");
}
public static void Quit(){
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss a dd/MM/yy");
Date date = new Date();
System.out.println("Your session has ended. The current time is " + (formatter.format(date)));
}
public static void main(String[] args) {
StringMenu s = new StringMenu();
int choice;
do
{
System.out.print("\n============================\n");
System.out.println("Enter the number of your choice: ");
System.out.println("(1) Enter a string");
System.out.println("(2) Display the string with all its spaces removed");
System.out.println("(3) Display the string backward");
System.out.println("(4) Quit");
Scanner input = new Scanner(System.in);
choice = input.nextInt();
switch (choice) {
case 1:
s.EnterString();
break;
case 2:
s.NoSpaces();
break;
case 3:
s.DisplayBackward();
break;
case 4:
Quit();
break;
default: System.out.println("Enter numbers from 1 to 4 only");
}
}
while (choice!=4);
}
If option 1 was chosen - with 'hello world' as the input - then 2 was picked 'hello world' should be displayed; if 3 was chosen afterwards 'dlrow olleh' should be displayed.
An error message appears for line 21 saying that it cannot find the symbol method setstring(String) with a location of variable s of type String.
If line 21 points to
public static void editString(String s){
s.setstring(stringinput);
}
, the error message is very obviously. The argument is String type and String does not have setstring method.
If you want to invoke setstring, the method definition should be as below at least.
public static void editString(StringMenu sm) { sm.setstring(stringinput); }
just create a variable and set the returned value to the created variable , then pass that variable as the argument of the method you want to pass in, then that value will be accessible in the method you've just passed.
Here is your program run as expected with all modifications.
Tested in IntellijIdea.
public class StringMenu {
private static String stringInput;
public static void main(String[] args) {
StringMenu s = new StringMenu();
Scanner input = new Scanner(System.in);
int choice;
do {
System.out.print("\n============================\n");
System.out.println("Enter the number of your choice: ");
System.out.println("(1) Enter a string");
System.out.println("(2) Display the string with all its spaces removed");
System.out.println("(3) Display the string backward");
System.out.println("(4) Quit");
choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("You enter String -> " + s.enterString());
break;
case 2:
System.out.println("string after Remove space -> " + s.noSpaces(stringInput));
break;
case 3:
System.out.println("Backward string -> " + s.displayBackward(stringInput));
break;
case 4:
s.Quit();
break;
default:
System.out.println("Enter numbers from 1 to 4 only");
}
} while (choice != 4);
}
public String enterString() {
System.out.print("Input a string: ");
Scanner scanner = new Scanner(System.in);
return stringInput = scanner.nextLine();
}
public String noSpaces(String stringInput) {
if (stringInput == null) {
stringInput = enterString();
}
char[] stringArray = stringInput.toCharArray();
String noSpaces = "";
for (int n = 0; n < stringArray.length; n++) {
if ((stringArray[n] != ' ') && (stringArray[n] != '\t')) {
noSpaces = noSpaces + stringArray[n];
}
}
return noSpaces;
}
public String displayBackward(String stringInput) {
String stringBackward = "";
if (stringInput == null) {
stringInput = enterString();
}
System.out.println("Original string ==>> " + stringInput);
char[] charArray = stringInput.toCharArray();
for (int i = charArray.length - 1; i >= 0; i--) {
stringBackward = stringBackward + charArray[i];
}
return stringBackward;
}
public void Quit() {
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss a dd/MM/yy");
Date date = new Date();
System.out.println("Your session has ended. The current time is " + (formatter.format(date)));
}
}
I have this hangman program but have an issue with asking the user if they want to play again, it always just ends the program. How can i fix this issue. Thanks for future reply's.
package hangman. I hope editing is okay with this
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hangman {
static Scanner keyboard = new Scanner(System.in);
static int size, size2;
static boolean play = false;
static String word;
static String[] ARRAY = new String[0];
static String ANSI_RESET = "\u001B[0m";
static String ANSI_BLUE = "\u001B[34m";
static String ANSI_GREEN = "\u001B[32m";
static String ANSI_RED = "\u001B[31m";
static String ANSI_LIGHTBLUE = "\u001B[36m";
//^declarations for variables and colors for display^
public static void main(String[] args) {
randomWordPicking();
//^calls method^
}
public static void setUpGame() {
System.err.printf("Welcome to hangman.\n");
try {
Scanner scFile = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
String line;
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line);
size++;
}
ARRAY = new String[size];
Scanner scFile1 = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
while (scFile1.hasNext()) {
String getWord;
line = scFile1.nextLine();
Scanner scLine = new Scanner(line);
word = scLine.next();
ARRAY[size2] = word;
size2++;
//calls method for picking word^
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void randomWordPicking() {
setUpGame();
int LEFT = 6;
do {
int random = (int) (Math.random() * ARRAY.length);
//^genertates a random number^
String randomWord = ARRAY[random];
String word = randomWord;
//^chosses a random word and asgins it to a variable^
char[] ranWord = randomWord.toCharArray();
char[] dash = word.toCharArray();
//^Creates a char array for the random word chosen and for the dashs which are displayed^
for (int i = 0; i < dash.length; i++) {
dash[i] = '-';
System.out.print(dash[i]);
//^displays dashs to the user^
}
for (int A = 1; A <= dash.length;) {
System.out.print(ANSI_BLUE + "\nGuess a Letter: " + ANSI_RESET);
String userletters = keyboard.next();
//^gets user input^
if (!userletters.equalsIgnoreCase(randomWord)) {
//^allows program to enter loop if user has entered a letter^
for (int i = 0; i < userletters.length(); i++) {
char userLetter = userletters.charAt(i);
String T = Character.toString(userLetter);
for (int B = 0; B < ranWord.length; B++) {
//^converts users input to a char and to a string^
if (userLetter == dash[B]) {
System.err.println("This " + userLetter + "' letter already exist");
B++;
//^tells user if the letter they entered already exists^
if (userLetter == dash[B - 1]) {
break;
}
} else if (userLetter == ranWord[B]) {
dash[B] = userLetter;
A--;
}
}
if (!(new String(ranWord).contains(T))) {
LEFT--;
System.out.println("You did not guess a correct letter, you have " + LEFT + " OF "
+ dash.length + " trys left to guess correctly");
}
//^shows how many trys the user has left to get the word right before game ends^
System.out.println(dash);
if (LEFT == 0) {
System.out.println("The word you had to guess was " + word);
break;
}
//^shows the user the word if they didnt guess correctly^
}
} else {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
if (LEFT == 0) {
break;
}
if ((new String(word)).equals(new String(dash))) {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
}
//^if user enters the word it will check and then display that they got the word correct^
System.out.println("Play agian? (y/n)");
String name = keyboard.next();
//^asks user if they want to play again^
if (name.equalsIgnoreCase("n")) {
play = true;
return;
}
//^stops program if user enters n to stop game^
} while (play = false);
}
}
If you want to compare two variables, do not use = operator, which means assignment. Use == instead. Additionally, in your case it should be !=:
while (play != false)
You should use
while (!play)
instead of
while (play = false)
I recenlty started to learn JAVA programming. I am using BlueJ compiler.
Can anyone tell me or give me a hint, how to make "System.out.println" not print out empty array values (I mean Null) values if array is not filled compleatly.
static String [] Country = new String [15];
static String [] City = new String [15];
static String [] Region = new String [15];
static Scanner sc = new Scanner(System.in);
static int x = 0, y = 0, z = 0;
static int a = 0, b=0,c=0, t=0;
public static void main (String [] args)
{
String entry = "-1";
while( !entry.equals ("4")){
menu();
entry = sc.nextLine();
if(!entry.equals("1") && (!entry.equals("2")) && (!entry.equals ("3")) && (!entry.equals ("4") && !entry.equals("-1")))
{ JOptionPane.showMessageDialog(null, "Please Enter Numbers as shown in 'MENU LIST'");
}
if (entry.equals ("1")) {
System.out.println("\f");
AddCity();
}
if (entry.equals("2")) {
System.out.println("\f");
Search();
}
if (entry.equals("3")) {
PrintAll();
}
}
JOptionPane.showMessageDialog(null, "Have a nice day");
}
public static void menu()
{
System.out.println(" ---------------- Menu-----------------");
System.out.println(" Please Use Numbers ONLY from 1 - 4 ");
System.out.println(" 1. Add new City");
System.out.println(" 2. Search for a City.");
System.out.println(" 3. Print All Cities.");
System.out.println(" 4. QUIT.");
}
public static void AddCity()
{
if(t >=13) {
JOptionPane.showMessageDialog(null, "Database capacity is almost full.");
PrintAll();
}
System.out.println("Please enter The name of Country.");
Country [x] = sc.nextLine();
x++;
System.out.println("Please enter the name of City.");
City [y] = sc.nextLine();
y++;
System.out.println("Please enter the Region where the city is located.");
Region [z] = sc.nextLine();
z++;
t++;
}
public static void Search()
{
}
public static void PrintAll()
{
while (a <14)
{
if (!Country.equals("Null") ) {
System.out.print("Country: ");
System.out.print(Country[a]+ " | ");
a++;
while(b <(a)) {
System.out.print("City: ");
System.out.print(City[b]+ " | ");
while(c<a) {
System.out.print("Region: ");
System.out.println(Region[c] + " | ");
c++;
}
b++;
}
}
System.out.println("");
}
}
}
Can anyone tell me or give me a hint, how to make "System.out.println"
not print out empty array values
You test, whether the value at the index position is null and only print, if not null. You need to consider, that the rest of your code, especially your counters a, b and c are outside of this condition.
while (a <14)
{
if (!Country.equals("Null") && country[a] != null) {
System.out.print("Country: ");
System.out.print(Country[a]+ " | ");
a++;
while(b <(a)) {
if(City[b]!=null) {
System.out.print("City: ");
System.out.print(City[b]+ " | ");
}
while(c<a) {
if(Region[c]!=null) {
System.out.print("Region: ");
System.out.println(Region[c] + " | ");
}
c++;
}
b++;
}
}
System.out.println("");
}
I am not sure where in your code you want to use this but is like this, in side you loop just check if you loop variable is not equal to null.
Ex:
if(variable != null) {
//do something
}