Why is my program crashing (java)? - java

I need to convert hexadecimal to decimal using different methods. When I enter numbers that are correct hexadecimal numbers, my program displays the decimal value and says that the number is valid. However, when I enter incorrect hexadecimal values, my program crashes.
Here is my code:
import java.io.*;
import java.util.Scanner;
public class pg3a {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String hex;
char choice = 'y';
boolean isValid = false;
do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
switch(choice){
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase();
int hexLength = hex.length();
isValid = valid(hex);
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
if (isValid) {
System.out.println(hex + " is valid");
}
break;
case 'n':
System.out.print("Quit");
}
}while (choice != 'n');
}
public static boolean valid (String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i=a; i< validString.length(); i++) {
if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
{
return false;
}
}
return true;
}
public static long convert (String hexValue) {
long decimal = 0;
boolean isNegative = false;
int a = 0;
if (hexValue.charAt(0) == '-') {
isNegative = true;
a = 1;
}
for (int i = a; i<hexValue.length(); i++) {
decimal = decimal*16;
if (hexValue.charAt(i) >= '0' && hexValue.charAt(i) <= '9') {
decimal += hexValue.charAt(i) - '0';
}
else if (hexValue.charAt(i) >= 'a' && hexValue.charAt(i) <= 'f') {
decimal += hexValue.charAt(i) - 'a' + 10;
}
}
if (isNegative == true) {
decimal *= -1;
}
return decimal;
}
}
why is it crashing and how can I fix it so that it displays "invalid" when incorrect hexadecimal digits are entered?

If you enter an invalid hex number, Integer.parseInt() will throw NumberFormatException. Change your code like this:
...
isValid = valid(hex);
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
...

do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
int base = 10;
switch(choice)
{
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase(); //I'm not sure if this step is necessary
try {
Integer value = Integer.parseInt(hex, 16);
System.out.println("Valid hex format");
System.out.println("Hex: " + hex);
System.out.println("Decimal: " + value);
}
catch (NumberFormatException e) {
System.out.println("Invalid hex format");
System.out.println("Input: " + hex);
}
break;
case 'n':
System.out.print("Quit");
break
}
} while (choice != 'n');
Now you can delete all your helper methods

Add Integer value = Integer.parseInt(hex,16); inside if statement and print invalid in else block.
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
else{
System.out.println("invalid");
}
Updated:
Change your valid method as follows:
public static boolean valid(String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i = a; i < validString.length(); i++) {
// if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F') || (validString.charAt(i) >= 0 && validString.charAt(i) <= 9))) {
// return false;
// }
char ch=validString.charAt(i);
if(!(Character.isDigit(ch) || (Character.isLetter(ch) && ((ch-'A')<=5))) ){
return false;
}
}
return true;
}

Related

Comparing Two Strings One Character at a Time in Java

I am trying to compare two different strings, one character at a time. I need to return the correct number of digits until they do not equal each other anymore. However, I can't include the character of '.' in the return statement. How would I go about doing this?
import java.util.Scanner;
import java.math.BigDecimal;
public class PiEstimate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a;
String b;
char y;
char c;
char d;
String userInput;
do {
System.out.print("Enter a number of randomly generated points:");
userInput = in.nextLine();
if (!isValid(userInput)) {
System.out.print("\n" + "You entered an invalid integer. Please enter a valid integer greater than 0: ");
userInput = in.nextLine();
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
} else {
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
}
System.out.println("\n" + "Would you like to play again? Enter 'Y' for yes or 'N' for no: ");
String optionToPlay = in.nextLine();
c = optionToPlay.charAt(0);
d = Character.toUpperCase(c);
if (d == 'n' || d == 'N') {
BigDecimal estimate2= new BigDecimal( (Math.PI / 4) * 4);
System.out.println("\n" + "The best estimate is: " + estimate2);
}
} while (d == 'Y');
} // end psvm
public static boolean isValid(String a) {
boolean isFlag = true;
char holder;
for (int i = 0; i < a.length(); i++) {
holder = a.charAt(i);
if (!Character.isDigit(a.charAt(i))) {
return false;
} if (i == 0 && holder == '-') {
return false;
}
} // end for
return isFlag;
} // end isValid
public static double calculation(String a) { // String a means 'looking for a string
double calc = Double.parseDouble(a);
int i;
double x;
double y;
double c = 0;
double runningCounter = 0;
double totalCounter;
for (i = 0; i < calc; i++) {
x = Math.random();
y = Math.random();
c = Math.sqrt((x * x) + (y * y));
if (c <= 1) {
runningCounter++;
}
} // end for
totalCounter = ((runningCounter / calc) * 4);
calc = totalCounter;
return calc;
}
public static int comparison (String bear, String userInput) {
int i = 0;
String s = calculation(userInput) + "";
int b;
int counter2 = 0;
for (i=0; i < s.length(); i++) {
if (s.charAt(i) != bear.charAt(i)) {
return i;
}
}
return i;
} // end comparison
} // end class
Code from IDE

Changing my program to use ArrayList

So I have been given a project in where I must validate ISBN-10 and ISBN-13 numbers. My issue is that I want to use an ArrayList based on what the user inputs(the user adds as many numbers as they want to the ArrayList). Here is my code (without an ArrayList). How can I modify this so that the user can put as many ISBN number as they want?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
//Get the ISBN
System.out.print("Enter an ISBN number ");
isbn = input.nextLine();
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
}else{
isValid = false;
}
//Print check Status
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{
System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
//
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
}
public static List<String> scanNumberToListUntilAppears(String end) {
if(end == null || end.isEmpty())
end = "end";
List<String> numbers = new ArrayList<>();
String message = "Enter an ISBN number: ";
try (Scanner input = new Scanner(System.in)) {
System.out.print(message);
while(input.hasNext()) {
String isbn = input.nextLine();
if(isbn.equalsIgnoreCase(end)) {
if(!numbers.isEmpty())
break;
} else {
numbers.add(isbn);
if(numbers.size() == 1)
message = "Enter the next ISBN number or '" + end + "': ";
}
System.out.print(message);
}
}
return numbers;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
String ans;
ArrayList<String> isbns = new ArrayList<String>();
// user will enter at least 1 ISBN
do{
//Get the ISBN
System.out.println("Enter an ISBN number ");
isbns.add(input.nextLine());
//loops till answer is yes or no
while(true){
System.out.println("Would you like to add another ISBN?");
ans = input.nextLine();
if(ans.equalsIgnoreCase("no"))
break;
else if (!(ans.equalsIgnoreCase("yes"))
System.out.println("Please say Yes or No");
}
}while(!(ans.equalsIgnoreCase("yes"));
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
for(int i = 0; i<isbns.size(); i++)
isbns.set(i, isbns.get(i).replaceAll("( |-)", ""));
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
for(String isbn : isbns){
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
print(isbn, isValid);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
print(isbn, isValid);
}else{
isValid = false;
print(isbn, isValid);
}
}
public static void print(String isbn, boolean isValid){
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{ System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}

Creating a Palindrome identifier

How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)

How to convert a do while loop to a while loop

How do I convert my do-while loop to a while loop?
int numAttempts = 0;
do
{
System.out.println("Do you want to convert to Peso or Yen?");
pesoOrYen = readKeyboard.nextLine();
if(pesoOrYen.equalsIgnoreCase("Peso")||pesoOrYen.equalsIgnoreCase("Yen"))
{
notPesoOrYen = false;
}
else if (numAttempts < 2)
{
System.out.println("Sorry, but '"+pesoOrYen+"' is not a valid currency type. Try again:");
notPesoOrYen = true;
}
numAttempts++;
} while(notPesoOrYen==true && numAttempts < 3);
I tried to do while(notPesoOrYen==true && numAttempts < 3) then the statement but it did not work.
MY FULL CODE
package currencyconverter;
import java.util.Scanner;
import java.text.NumberFormat;
public class CurrencyConverter
{
public static void main(String[] args)
{
Scanner readKeyboard = new Scanner(System.in);
double doubleUsersCaptial;
boolean notPesoOrYen=true;
String pesoOrYen;
double usersConvertedCapital;
boolean userInputToRunProgramAgain=true;
final double US_DOLLAR_TO_PESO = 13.14;
final double US_DOLLAR_TO_YEN = 106.02;
do
{
System.out.println ("How much money in US dollars do you have?");
String usersCaptial = readKeyboard.nextLine();
doubleUsersCaptial = Double.parseDouble(usersCaptial);
int numAttempts = 0;
do
{
System.out.println ("Do you want to convert to Peso or Yen?");
pesoOrYen = readKeyboard.nextLine();
if(pesoOrYen.equalsIgnoreCase("Peso")||pesoOrYen.equalsIgnoreCase("Yen"))
{
notPesoOrYen = false;
}
else if (numAttempts < 2)
{
System.out.println("Sorry, but '"+pesoOrYen+"' is not a valid currency type. Try again:");
notPesoOrYen = true;
}
numAttempts++;
}while(notPesoOrYen==true && numAttempts < 3);
if(numAttempts==3)
{
System.out.println("Sorry, but '"+pesoOrYen+"' is not a valid currency type.");
System.out.println("You entered the wrong currency type too many times\nGood Bye");
System.exit(0);
}
if (pesoOrYen.equalsIgnoreCase("Peso"))
{
usersConvertedCapital = doubleUsersCaptial*US_DOLLAR_TO_PESO;
}
else
{
usersConvertedCapital = doubleUsersCaptial*US_DOLLAR_TO_YEN;
}
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String formatUsersCaptial = formatter.format(doubleUsersCaptial);
String formatUsersConvertedCapital = formatter.format(usersConvertedCapital);
System.out.println(formatUsersCaptial+"US Dollars = "
+formatUsersConvertedCapital+" "+pesoOrYen);
System.out.println("Would you like to run the Program Again?(enter 'yes' or 'no')");
String runProgramAgain = readKeyboard.nextLine();
if (runProgramAgain.equalsIgnoreCase("yes"))
{
userInputToRunProgramAgain = true;
}
else if (runProgramAgain.equalsIgnoreCase("no"))
{
System.out.println("Goood Bye");
System.exit(0);
}
else
{
System.out.println ("You entered something other than 'yes' or 'no'\n"
+"Good Bye");
System.exit(0);
}
}while (userInputToRunProgramAgain==true);
}
}
while and do... while are almost the same, do... while simply performs an iteration before evaluating for the first time the exit condition, whereas while evaluates it even for the first iteration (so eventually the body of a while loop can never be reacher whereas a do... while body will always be executed at least once).
Your code snippet is not complete but I guess you didn't initialized notPesoOrYen to true before the loop and that's why it is not working. Finally, don't write while(notPesoOrYen==true && numAttempts < 3) but while(notPesoOrYen && numAttempts < 3), the == true comparison is unnecessary.
Initialise your boolean variable outside while loop:
int numAttempts = 0;
boolean notPesoOrYen=true;
while (notPesoOrYen && numAttempts < 3) {
System.out.println("Do you want to convert to Peso or Yen?");
pesoOrYen = readKeyboard.nextLine();
if (pesoOrYen.equalsIgnoreCase("Peso") || pesoOrYen.equalsIgnoreCase("Yen")) {
notPesoOrYen = false;
} else if (numAttempts < 2) {
System.out.println("Sorry, but '" + pesoOrYen + "' is not a valid currency type. Try again:");
notPesoOrYen = true;
}
++numAttempts;
};

Command Line Calulator, Java

Input from the Java commandline: "4 + 6 + 5 - 5".
Wanted outcome: "is 10".
Actual outcome: "is 5".
class Calculator
{
int v_in1, v_in2, v_in3, v_in4, v_answer, result;
String v_sign1, v_sign2, v_sign3;
public Calculator()
{
}
public void count(String[] args)
{
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+": {
v_answer += v_in1;
break;
}
case "-": {
v_answer -= v_in1;
break;
}
}
}
System.out.print("is " + v_answer);
}
}
There might be some additional problems e.g too many variable declared etc, but what I'm concerned about it the for- if- switch part, I'm unable to pin- point the problem.
Thank you :)
The problem is that you are applying the operation to the previous number, not to the next to come. Instead you should memorize the operator and update the result when you see a number, e.g. like this:
int sign = +1, result = 0;
for (String arg : args) {
switch (arg) {
case "+":
sign = +1;
break;
case "-":
sign = -1;
break;
default:
result += sign * Integer.parseInt(arg);
}
}
This is happening because your last integer wont be taken into account as it is just stored in v_in1, but since there is no +,- so it doesnt get added or subtracted. Try this:
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+":
{
v_answer = v_in1 + Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
case "-":
{
v_answer = v_in1 - Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
}
}
I do not know all requirements for this task, but I recommend to convert the whole expression to postfix notation, then parse it using stack to evaluate the result.
I took a look at your method, and I recommend you simplify your code (something like this for long count(String[] args))
long result = 0; // Note, this shadows your Object's result. I'm not sure why you
// had hard-coded fields like that. I don't think you need them.
// Also, this returns a long.
boolean negative = false;
for (String arg : args) {
String oper = arg.trim();
if (oper.equals("+")) { // Is it a plus sign?
negative = false;
} else if (oper.equals("-")) { // Is it a minus sign?
negative = !negative; // - a negative value is addition
} else {
try {
int i = Integer.parseInt(oper); // Parse the integer
if (negative) {
i = -i;
negative = false;
}
result += i; // add the result
} catch (NumberFormatException nfe) {
System.err.println(oper + " is not +, - or a number");
}
}
}
return result;
This is what worked in the exercise.
class Calculator
{
int v_answer = 0;
int v_in1 = 0;
public Calculator()
{
}
public void count(String args[])
{
System.out.println();
System.out.print("Result of the calculation ");
for(int i = 0; i < args.length; i++)
{
System.out.print(args[i]+ " ");
if(i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
}
if(i == 0)
{
v_answer += Integer.parseInt(args[0]);
}
if(args[i].equals("+"))
{
v_answer += Integer.parseInt(args[i+1]);
}
else if(args[i].equals("-"))
{
v_answer -= Integer.parseInt(args[i+1]);
}
}
System.out.print("is " + v_answer);
System.out.println();
}
}

Categories

Resources