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
}
Related
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
package javaapplication4;
import javax.swing.*;
public class JavaApplication4 {
public static void main(String[] args) {
// TODO code application logic here
int num1;
num1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter a value"));
if(num1<50 && num1>100)
System.out.println("value is correct");
else
System.out.println("value is incorrect");
}
}
Solution 1
You can repeat the operation 2 times like this :
public static void main(String[] args) {
int i = 0, n = 2;//repeat n time
while (i < n) {
// TODO code application logic here
int num1;
num1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter a value"));
if (num1 < 50 && num1 > 100) {
System.out.println("value is correct");
} else {
System.out.println("value is incorrect");
}
i++;
}
}
Solution 2
You can use an array to store your values and check them later for example :
public static void main(String[] args) {
int i = 0, n = 2;
// TODO code application logic here
int num1[] = new int[n];
while (i < n) {
num1[i] = Integer.parseInt(JOptionPane.showInputDialog("Please value " + (i+1)));
i++;
}
if (num1[0] < 50 && num1[1] > 100) {
System.out.println("value is correct");
} else {
System.out.println("value is incorrect");
}
}
This will ask you for the n value, in your case will ask you to enter 2 values so it will stored in your array, then you can check this values of array.
EDIT
You have to use a separator and you can split with this separator for example your input should look like this :
6999,888
--1---2
so when you split with , String[] spl = res.split(","); you will get an array of String like [6999,888], then you can use this two value to make your condition :
int v1 = Integer.parseInt(spl[0]);//convert String to int
int v2 = Integer.parseInt(spl[1]);//convert String to int
So your program should look like this :
public static void main(String[] args) {
String res = JOptionPane.showInputDialog("Please enter a value separated with , :");
String[] spl = res.split(",");
System.out.println(Arrays.toString(spl));
//you have to make some check to avoid any problem
int v1 = Integer.parseInt(spl[0]);
int v2 = Integer.parseInt(spl[1]);
if (v1 < 50 && v2 > 100) {
System.out.println("value is correct");
} else {
System.out.println("value is incorrect");
}
}
Edit2
You can show your result in JOptionPane like this :
if (v1 < 50 && v2 > 100) {
JOptionPane.showMessageDialog(null, "value is correct");
} else {
JOptionPane.showMessageDialog(null, "value is incorrect");
}
EDIT3
To get the max you have to check it like this :
if (v1 > v2) {
JOptionPane.showMessageDialog(null, "larger value is : " + v1);
} else {
JOptionPane.showMessageDialog(null, "larger value is : " + v2);
}
Or in one line you can use :
JOptionPane.showMessageDialog(null, "larger value is : " + (v1 > v2 ? v1 : v2));
I have this code that involves task to do with the ArrayList names
that includes functions like adding elements in the ArrayList, displaying the elements of the ArrayList, deleting an element in an ArrayList, editing an element in an ArrayList.
My question is when I add a new name in the ArrayList, when the code loops back and I want to view the elements in the ArrayList, it turns out empty.
import java.util.ArrayList;
import java.util.Scanner;
public class mainRunner {
public static void main(String[] args) {
String con;
do {
menuCaller();
System.out.println("Do you want to continue[Y/N]");
Scanner confirm = new Scanner(System.in);
con = confirm.nextLine();
} while (con.equalsIgnoreCase("y"));
}
public static void menuCaller() {
int choice;
ArrayList names = new ArrayList();
int firstIndex =0;
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
Scanner scaned = new Scanner(System.in);
System.out.println("Menu"
+"\n[1] Add Name"
+ "\n[2] Display All Record"
+ "\n[3] Delete a Record"
+ "\n[4] Edit a R1ecord "
+ "\n[5] Exit");
choice = scaned.nextInt();
if (choice == 1) {
System.out.println("***ADDING NAMES***");
System.out.println("Enter the name of the Student");
String addName = scan.next();
names.add(addName);
System.out.println("Record Added !!!");
}
else if (choice == 2) {
System.out.println("***Database Content**");
System.out.println("------------------------");
System.out.println("Record # | Name ");
for (int index = firstIndex; index < names.size(); ++index) {
System.out.println("--------------------");
System.out.println(" " + index + " | " +names.get(index));
}
}
else if (choice == 3) {
System.out.println("***Delete A Record***");
System.out.print("Enter a number to be deleted: ");
int numDelete = scan.nextInt();
names.remove(numDelete);
System.out.println("Record Deleted");
}
else if (choice == 4) {
System.out.println("***Edit Record***");
System.out.println("***Database Content**");
System.out.println("------------------------");
System.out.println("Record # | Name ");
for (int index = firstIndex; index < names.size(); ++index) {
System.out.println("--------------------");
System.out.println(" " + index + " | " +names.get(index));
}
System.out.println("Enter the Name to be Edited");
String nameEdited = scan.next();
if (names.indexOf(nameEdited) >= 0) {
System.out.print("Change to: ");
String nameChange = scan2.next();
names.set(names.indexOf(nameEdited), nameChange);
}
else {
System.out.println("Record Not Existing");
}
}
else if (choice == 5) {
System.out.println("Thank you for using the Program");
System.exit(choice);
}
else {
System.out.println("Wrong Choice");
}
}
}
Each time you call menuCaller, you're creating a new list.
Perhaps you should create it in the main method and pass the reference into menuCaller:
public static void main(String[] args) {
String con;
List<String> names = new ArrayList<>();
do{
menuCaller(names);
System.out.println("Do you want to continue[Y/N]");
Scanner confirm = new Scanner(System.in);
con = confirm.nextLine();
}while(con.equalsIgnoreCase("y"));
}
public static void menuCaller(List<String> names) {
...
// (No declaration of names here - it's a parameter now...)
...
}
In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.
Hi there,
I'm a newbie in java and I have a problem with this code. I'm thinking if it is a problem in loop or something..
public static void main(String[] args) {
try {
Scanner scn = new Scanner(System.in);
int z = 0;
String input;
int[] ABArray = new int[2];
while (z == 0) {
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input = scn.nextLine().toLowerCase();
for (int i = 0; i < input.length(); i++) {
char AB = input.charAt(i);
ABArray[AB - 'a']++;
}
if (ABArray[0] == 0 || ABArray[1] == 0) {
System.out.println("Not Equal");
System.out.println("");
} else if (ABArray[0] == ABArray[1]) {
System.out.println("Equal");
System.out.println("");
} else if (ABArray[0] != ABArray[1]) {
System.out.println("Not Equal");
if (ABArray[0] > ABArray[1]) {
System.out.println("The number of A is greater than B.");
} else if (ABArray[0] < ABArray[1]) {
System.out.println("The number of B is greater than A.");
}
System.out.println("");
}
}
} catch (ArrayIndexOutOfBoundsException X) { } //Terminates the program
}
The problem is this
I/O
Input:
ABABAB
Output:
Equal
Input:
AABBB
Output:
Not Equal
The number of B is greater than A.
Input:
AABB //It is equal.
Output:
Not Equal //It says not.
The number of B is greater than A.
As you see, the problem is when I input equal A and B at the first, it says equal, when I input not equal A and B but at the third when I input equal A and B it says not equal.
Problem solved.
Thanks for the help.
You have to set all the values in ABArray to zero every time you start to work inside the while loop. Right now on the third time you start the while loop (with AABB input) you still keep the values which were left from the previous run of the loop - 5 in the 0-indexed element of an array and 6 in the 1-indexed element of an array, thus the program gives you the wrong output.
How about you simply read in the input into a string, then loop through it, counting the number of occurrences of each character you are interested in (here 'a' and 'b'), checking whether their counts are equal? So this works for example:
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
String input;
while (true) {
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input = scanner.nextLine().toLowerCase();
if (input.equals("X")) {
break;
} else {
int countA = 0;
int countB = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'a') {
countA++;
} else if (input.charAt(i) == 'b') {
countB++;
}
}
if (countA == countB) {
System.out.println("Equal!");
} else {
System.out.println("Not equal!");
}
}
}
} catch (ArrayIndexOutOfBoundsException e) // Terminates the program
{
}
}
You can use this code:
public static void main( String[] args )
{
try
{
Scanner scn = new Scanner(System.in);
int z=0;
String input;
int[] ABArray = null;
while(z==0)
{
ABArray = new int[2];
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input=scn.nextLine().toLowerCase();
for ( int i = 0; i < input.length(); i++ )
{
char AB=input.charAt(i);
ABArray[AB-'a']++;
}
if(ABArray[0]==0||ABArray[1]==0)
{
System.out.println("Not Equal");
System.out.println("");
}
else if(ABArray[0]==ABArray[1])
{
System.out.println("Equal");
System.out.println("");
}
else if(ABArray[0]!=ABArray[1])
{
System.out.println("Not Equal");
if(ABArray[0]>ABArray[1])
{
System.out.println("The number of A is greater than B.");
}
else if(ABArray[0]<ABArray[1])
{
System.out.println("The number of B is greater than A.");
}
System.out.println("");
}
}
}
catch(ArrayIndexOutOfBoundsException X) //Terminates the program
{
X.printStackTrace();
}
}