Refer to a method and check Input - java

I have created a method that checks if an Input is between the size of column in a csv File.
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
}
else { System.out.println("The Column doesn't exists.");}
return true; }}
And in the main method i refer to the isValidNumber-Method
// some previous code
do { String userInput = JOptionPane.showInputDialog);
} while(isValidNumber(userInput));}
//next code
So i can't get out of the Loop even if the userInput is correct and exists in the csv-file. Can someone help me out?

Your isValidNumber always returns true and that's why you are not able to get out of the loop.
Try using below--
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
return true;
}
else { System.out.println("The Column doesn't exists."); return false;}
}

Assuming that your issue is that anything you enter is valid, the problem lies within the isValidNumber method itself:
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
}
else {
System.out.println("The Column doesn't exists.");
}
return true;
}
This will yield true regardless, what you need to do is to move your return statements. After printing, you will need to return true/false accordingly:
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
return true;
}
else {
System.out.println("The Column doesn't exists.");
return false;
}
}
Alternatively:
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
return true;
}
System.out.println("The Column doesn't exists.");
return false;
}

Related

How would I write a toString and reduce duplicate outputs?

So, I've created a simple app for moving a bug along a wire. The code works well (for the most part) though, I am having a few issues.
When reaching the end of the wire, the program terminates all well and good but I'm getting a double output that it's fallen off the wire when it reaches the end.
I am supposed to be writing a toString for this, but am having a bit of a hard time grasping why and how I should go about doing this.
If someone could assist with this, I'd greatly appreciate it.
import java.util.Scanner;
public class ClassPracticeMain {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
int userInput;
Bug bug1 = new Bug();
bug1.setInitialPosition();
bug1.setInitialDirection();
System.out.println("Your starting position is " + bug1.initialPosition
+ " and you are facing " + bug1.getCurrentDirection()
);
while (bug1.getExit(1) != 0) {
System.out.println("Which way would you like to move? 1 for left/ 2 for right or 0 for exit");
userInput = input.nextInt();
bug1.move(userInput);
bug1.getCurrentDirection();
bug1.getCurrentPosition();
System.out.println("You are now at " + bug1.currentPosition + " and you are facing " + bug1.getCurrentDirection());
bug1.getExit(userInput);
}
}
}
public class Bug {
final int WIRELEFTEND=-15;
final int WIRERIGHTEND=15;
int initialPosition=0, currentPosition=0, direction,exit=1;
String currentDirection;
String left = "left";
String right = "right";
public int setInitialPosition(){
return initialPosition;
}
public int setInitialDirection(){
direction=1;
return direction;
}
public int getCurrentPosition(){
return currentPosition;
}
public String getCurrentDirection(){
if (direction== 1){
currentDirection=left;
} else if (direction == 2){
currentDirection=right;
}
return currentDirection;
}
public int move(int move){
if(move==1 && direction==1){
currentPosition=currentPosition-1;
return currentPosition;
} else if (move==1 && direction==2){
direction=1;
return currentPosition;
} else if (move==2 && direction==1){
direction=2;
return currentPosition;
} else if (move==2 && direction ==2){
currentPosition=currentPosition+1;
return currentPosition;
}
return 0;
}
public int getExit(int exit){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
exit=0;
} else{
exit=exit;
}
return 1;
}
}
You probably want to write
public int getExitStatus(){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
return 0;
}
return 1;
}
instead of your current getExist(int) function. It always returns 1, and setting the exit argument doesn't do anything.

Java Input Validation

So I am working with a program that is supposed to incorporate try-catch blocks for exception handling. What I can't figure out is how to write a simple if statement for checking input from the user via Scanner to make sure it is a double and not a letter or a character so that if it is the program will catch it, display the error message, and tell the user to re-enter another value until a suitable input is entered. What I am looking for is a simple if(_width equals a letter/character) then return false along with an error message to go along with my already present if statement that checks whether the input is greater than zero.
my current code is below:
public class Rectangle {
//two double data fields width and height, default values are 1 for both.
private double width = 1;
private double height = 1;
private String errorMessage = "";
//no-arg constructor creates default rectangle
public Rectangle() {
}
//fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
public Rectangle (double _width, double _height) throws Exception {
setWidth(_width);
setHeight(_height);
}
//get functions
public double getArea(){
return (width * height);
}
public double getPerimeter() {
return (2*(width + height));
}
public String getErrorMessage() {
return errorMessage;
}
//set functions
public void setWidth(double _width) throws Exception {
if( !isValidWidth(_width)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
width = _width;
}
public void setHeight(double _height) throws Exception {
if ( !isValidHeight(_height)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
height = _height;
}
//isValid methods
public boolean isValidWidth(double _width) {
if(_width > 0){
return true;
}
else {
errorMessage = "Invalid value for width, must be greater than zero";
return false;
}
if ()
}
public boolean isValidHeight(double _height) {
if(_height > 0){
return true;
}
else {
errorMessage = "Invalid value for height, must be greater than zero";
return false;
}
}
}
My class is being called by another test program that i have written correctly. Any help is appreciated! Thank you.
maybe something like:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
try {
Double.parseDouble(str);
}
catch( Exception e ){
System.out.println(errorMessage);
}
or iterate through the input and check if each character is digit:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(int i=0;i<str.length();i++){
char token = str.charAt(i);
if(!Character.isDigit(token) && token!='.' ) {
System.out.println(token + " doesnt work");
break;
}
}
On declaring your scanner you could also:
double num;
String errorMessage = "error";
while(true) {
Scanner in = new Scanner(System.in);
if (in.hasNextDouble()) {
num = in.nextDouble();
System.out.println(num);
break;
}
else System.out.println(errorMessage);
}
Maybe this code helps you:
double Input=0;
while(!(Input > 0)){{
System.out.println("Enter Valid Number");
Input = new Scanner(System.in).nextDouble();
}

Remove User Duplicate From Array String

I am trying to create a program that accepts as many Social Security Numbers as the user wants to input. The only restriction is that the numbers must follow the format XXX-XX-XXXX and not accept duplicated entries. This is what I have so far:
Subclass 2
package SSNServerStorageExpanded;
class SSNArray{
final String[] ssnNumber;
int arrayCount;
public SSNArray(){//defult contructor
ssnNumber = new String[9999];
arrayCount = 0;
}
public SSNArray(int arraySize){
ssnNumber = new String[arraySize];
arrayCount = 0;
}
public String[] getSSNNumber(){
return ssnNumber;
}
public int getArrayCount(){
return arrayCount;
}
public boolean validateSSNNumber(String SSNFormat){
return SSNFormat.matches("\\d{3}-\\d{2}-\\d{4}");
}
public String addSSN(String SSNFormat){
if(validateSSNNumber(SSNFormat)){
return ssnNumber[arrayCount++] = SSNFormat;
}else{
return null;
}
}
#Override
public String toString(){
String str = "\nThe Social Security Number(s) you entered is(are):\n";
for(int x = 0; x < arrayCount; x++){/
str += ssnNumber[x] + "\n";
}return str;
}
}
Subclass 1
package SSNServerStorageExpanded;
public class SSNArrayExpanded extends SSNArray{
public SSNArrayExpanded(){
super();
}
public SSNArrayExpanded(int arraySize){
super(arraySize);
}
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = false;
for(int y = 0; y < arrayCount; y++){
if(ssnNumber[y].equals(ssnNumber[arrayCount])){
System.out.println("No duplicates allowed, please try again");
duplicate = true;
break;
}
}
if(!duplicate){
arrayCount++;
}
}
return true;
}
}
Mainclass
package SSNServerStorageExpanded;
import java.util.Scanner;
public class SSNArrayTestExpanded{
public static void main(String[] args){
SSNArrayExpanded SSNArrayExpandedObject = new SSNArrayExpanded();
Scanner input = new Scanner(System.in);
System.out.println("Initiating SSN Server Storage Expanded");
System.out.println("► Type 'EXIT' at any moment to close the program ◄\n");
boolean run = true;
while(run){
System.out.print("Enter your Social Security Number(XXX-XX-XXXX): ");
String ssnNumber = input.next();
if(ssnNumber.equalsIgnoreCase("EXIT")){
System.out.print(SSNArrayExpandedObject.validateSSNNumber(ssnNumber));
return;
}else if(SSNArrayExpandedObject.validateSSNNumber(ssnNumber)){
SSNArrayExpandedObject.addSSN(ssnNumber);
}else{
System.out.println("!Please use the format XXX-XX-XXXX!");
}
}
}
}
What am I doing wrong with my public boolean validateSSNNumber method under Subclass 1 or are there more errors in my code that I am not aware of?
In your subclass1 can you try this. You need to compare the SSNFormat String entered by user with the array values (you were comparing array values itself). Do not increase the array count here instead do it in addSSN function as you were doing.
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = false;
for(int y = 0; y < arrayCount; y++){
if(ssnNumber[y].equals(SSNFormat)){
System.out.println("No duplicates allowed, please try again");
duplicate = true;
break;
}
}
if(!duplicate){
return true;
}
}
return false;
}
In the SSNArray class use this function for adding SSN number without validating the SSNFormat again.
public String addSSN(String SSNFormat){
return ssnNumber[arrayCount++] = SSNFormat;
}
You can try using a Set, which will easily help you to check for any duplicates and will reduce your iteration over array.
Why cant you go for LinkedHashSet data structure for storing the ssn number.?, provides easy retrieval and duplicate check in an order of O(1).
final LinkedHashSet<String> ssnNumber;
also the code
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = ssnNumber.add(SSNFormat);
if(duplicate){
System.out.println("No duplicates allowed, please try again");
return false;
}
return true;
}
return false
}
Here is your complete Solution, with this you can add N-number of SSN-Number as you want,
import java.util.HashSet;
import java.util.Scanner;
class SSNSet{
final HashSet<String> allSsnNumber = new HashSet<String>();
public HashSet<String> getAllSsnNumber() {
return allSsnNumber;
}
public boolean validateSSNNumber(String SSNFormat){
return SSNFormat.matches("\\d{3}-\\d{2}-\\d{4}");
}
public boolean addSSN(String SSNFormat){
if(validateSSNNumber(SSNFormat)){
boolean flag;
if(allSsnNumber.add(SSNFormat)){
System.out.println("Added Successfully");
flag = true;
}else{
System.out.println("Duplicate Not Allow");
flag = false;
}
return flag;
}else{
System.out.println("!Please use the format XXX-XX-XXXX!");
return false;
}
}
}
public class SSNArrayTestExpanded{
public static void main(String[] args){
SSNSet SSNArrayExpandedObject = new SSNSet();
Scanner input = new Scanner(System.in);
System.out.println("Initiating SSN Server Storage Expanded");
System.out.println(" Type 'EXIT' at any moment to close the program \n");
boolean run = true;
while(run){
System.out.print("Enter your Social Security Number(XXX-XX-XXXX): ");
String ssnNumber = input.next();
if(ssnNumber.equalsIgnoreCase("EXIT")){
break;
/*System.out.print(SSNArrayExpandedObject.validateSSNNumber(ssnNumber));
return;*/
}else{
SSNArrayExpandedObject.addSSN(ssnNumber);
}
}
System.out.println("===============================================");
System.out.println("You have entered SSN Numbers are : ");
System.out.println(SSNArrayExpandedObject.getAllSsnNumber());
System.out.println("===============================================");
System.out.println("Program Ended Successfully");
}
}
and Output is :
Initiating SSN Server Storage Expanded
Type 'EXIT' at any moment to close the program
Enter your Social Security Number(XXX-XX-XXXX): 111-11-1111
Added Successfully
Enter your Social Security Number(XXX-XX-XXXX): 222-22-222
!Please use the format XXX-XX-XXXX!
Enter your Social Security Number(XXX-XX-XXXX): 111-11-1111
Duplicate Not Allow
Enter your Social Security Number(XXX-XX-XXXX): 333-33-333
!Please use the format XXX-XX-XXXX!
Enter your Social Security Number(XXX-XX-XXXX): 333-33-3333
Added Successfully
Enter your Social Security Number(XXX-XX-XXXX): EXIT
===============================================
You have entered SSN Numbers are :
[111-11-1111, 333-33-3333]
===============================================
Program Ended Successfully
public boolean validateSSNNumber(String SSNFormat) {
if (super.validateSSNNumber(SSNFormat)) {
/*
*Hashset add() - Returns true if this set did not already contain
*the specified element.
*If this set already contains the element, the call leaves the set
* unchanged and returns
*/
boolean duplicate = !uniqueSSNNum.add(SSNFormat);
return duplicate;
}
return false;
}
//To use HastSet it's better if you override equals and hashcode
//using the fields that you'll use for comparison equality
// generated using eclipse
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + arrayCount;
result = prime * result + Arrays.hashCode(ssnNumber);
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SSNArray other = (SSNArray) obj;
if (arrayCount != other.arrayCount)
return false;
if (!Arrays.equals(ssnNumber, other.ssnNumber))
return false;
return true;
}

How do I check if a class' return of a method equals null?

In my program, I have a while loop that will display a list of shops and asks for an input, which corresponds with the shop ID. If the user enters an integer outside the array of shops, created with a Shop class, it will exit the loop and continue. Inside this loop is another while loop which calls the sellItem method of my Shop class below:
public Item sellItem()
{
displayItems();
int indexID = Shop.getInput();
if (indexID <= -1 || indexID >= wares.length)
{
System.out.println("Null"); // Testing purposes
return null;
}
else
{
return wares[indexID];
}
}
private void displayItems()
{
System.out.println("Name\t\t\t\tWeight\t\t\t\tPrice");
System.out.println("0. Return to Shops");
for(int i = 0; i < wares.length; i++)
{
System.out.print(i + 1 + ". ");
System.out.println(wares[i].getName() + "\t\t\t\t" + wares[i].getWeight() + "\t\t\t\t" + wares[i].getPrice());
}
}
private static int getInput()
{
Scanner scanInput = new Scanner(System.in);
int itemID = scanInput.nextInt();
int indexID = itemID - 1;
return indexID;
}
The while loop in my main class method is as follows:
boolean exitAllShops = true;
while(exitAllShops)
{
System.out.println("Where would you like to go?\nEnter the number which corresponds with the shop.\n1. Pete's Produce\n2. Moore's Meats\n3. Howards Hunting\n4. Foster's Farming\n5. Leighton's Liquor\n6. Carter's Clothing\n7. Hill's Household Products\n8. Lewis' Livery, Animals, and Wagon supplies\n9. Dr. Miller's Medicine\n10. Leave Shops (YOU WILL NOT BE ABLE TO RETURN)");
int shopInput = scan.nextInt();
if(shopInput >= 1 && shopInput <= allShops.length)
{
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
}
else
{
System.out.println("Are you sure you want to leave?\n1. Yes\n2. No");
int confirm = scan.nextInt();
if(confirm == 1)
{
exitAllShops = false;
}
}
The problem is here:
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
No matter what I do, I can't get "still null" to print to confirm that I'm correctly calling the return statement of the method sellItem of the class Shop. What am I doing wrong?
After calling allShops[...].sellItem(), allShops is still a valid array reference -- there's no way it could be null! You probably want to test the return value from sellItem:
if(allShops[shopInput-1].sellItem() == null)

Infinite while loop in java, not reading in sentinel

I've had this problem throughout multiple programs, but I can't remember how I fixed it last time. In the second while loop in my body, the second sentinel value is never read in for some reason. I've been trying to fix it for a while now, thought I might see if anyone had any clue.
import java.text.DecimalFormat; // imports the decimal format
public class Car {
// Makes three instance variables.
private String make;
private int year;
private double price;
// Makes the an object that formats doubles.
public static DecimalFormat twoDecPl = new DecimalFormat("$0.00");
// Constructor that assigns the instance variables
// to the values that the user made.
public Car(String carMake,int carYear, double carPrice)
{
make = carMake;
year = carYear;
price = carPrice;
}
// Retrieves variable make.
public String getMake()
{
return make;
}
// Retrieves variable year.
public int getYear()
{
return year;
}
// Retrieves variable price.
public double getPrice()
{
return price;
}
// Checks if two objects are equal.
public boolean equals(Car c1, Car c2)
{
boolean b = false;
if(c1.getMake().equals(c2.getMake()) && c1.getPrice() == c2.getPrice() &&
c1.getYear() == c2.getYear())
{
b = true;
return b;
}
else
{
return b;
}
}
// Turns the object into a readable string.
public String toString()
{
return "Description of car:" +
"\n Make : " + make +
"\n Year : " + year +
"\n Price: " + twoDecPl.format(price);
}
}
import java.util.Scanner; // imports a scanner
public class CarSearch {
public static void main(String[] args)
{
// initializes all variables
Scanner scan = new Scanner(System.in);
final int SIZE_ARR = 30;
Car[] carArr = new Car[SIZE_ARR];
final String SENT = "EndDatabase";
String carMake = "";
int carYear = 0;
double carPrice = 0;
int count = 0;
int pos = 0;
final String SECSENT = "EndSearchKeys";
final boolean DEBUG_SW = true;
// Loop that goes through the first list of values.
// It then stores the values in an array, then uses the
// values to make an object.
while(scan.hasNext())
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car car1 = new Car(carMake, carYear, carPrice);
carArr[count] = car1;
count++;
}
// Calls the method debugSwitch to show the debug information.
debugSwitch(carArr, DEBUG_SW, count);
// Calls the method printData to print the database.
printData(carArr, count);
// Loops through the second group of values and stores them in key.
// Then, it searches for a match in the database.
**while(scan.hasNext())**
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SECSENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car key = new Car(carMake, carYear, carPrice);
// Stores the output of seqSearch in pos.
// If the debug switch is on, then it prints these statements.
if(DEBUG_SW == true)
{
System.out.println("Search, make = " + key.getMake());
System.out.println("Search, year = " + key.getYear());
System.out.println("Search, price = " + key.getPrice());
}
System.out.println("key =");
System.out.println(key);
pos = seqSearch(carArr, count, key);
if(pos != -1)
{
System.out.println("This vehicle was found at index = " + pos);
}
else
{
System.out.println("This vehicle was not found in the database.");
}
}
}
// This method prints the database of cars.
private static void printData(Car[] carArr, int count)
{
for(int i = 0; i < count; i++)
{
System.out.println("Description of car:");
System.out.println(carArr[i]);
}
}
// Searches for a match in the database.
private static int seqSearch(Car[] carArr, int count, Car key)
{
for(int i = 0; i < count; i++)
{
boolean b = key.equals(key, carArr[i]);
if(b == true)
{
return i;
}
}
return -1;
}
// Prints debug statements if DEBUG_SW is set to true.
public static void debugSwitch(Car[] carArr, boolean DEBUG_SW, int count)
{
if(DEBUG_SW == true)
{
for(int i = 0; i < count; i++)
{
System.out.println("DB make = " + carArr[i].getMake());
System.out.println("DB year = " + carArr[i].getYear());
System.out.println("DB price = " + carArr[i].getPrice());
}
}
}
}
I think this is your problem, but I might be wrong:
Inside your while loop, you have these calls:
next()
nextInt()
nextDouble()
The problem is that the last call (nextDouble), will not eat the newline. So to fix this issue, you should add an extra nextLine() call at the end of the two loops.
What happens is that the next time you call next(), it will return the newline, instead of the CarMake-thing.

Categories