Java Program Won't Stop Accepting User Input - java

I'm writing a java program that takes an integer from the user and outputs that number in binary. My code does not give me any errors, but the program won't run like it should. The program asks for the user to input a number, but when I hit enter, it simply goes to the next line and the user can input infinitely. Where did I go wrong? I've tried debugging it but I can't seem to find the problem. Thank you so much in advance!
package example;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
int input = promptForDecimal(inScanner);
String output = decimalToBinary(input);
System.out.println("The decimal value " + input + " is " + output
+ " in binary.");
}
public static String decimalToBinary(int value) {
String binary = "";
int i = 0;
while (value > 0) {
i = value % 2;
if (i == 1) {
binary = binary + "1";
}
else {
binary = binary + "0";
}
}
return binary;
}
public static int promptForDecimal(Scanner inScanner) {
System.out.print("Enter an integer value (negative value to quit): ");
String val = inScanner.nextLine();
while (checkForValidDecimal(val) == false) {
System.out.println("Error - value must contain only digits");
System.out.println("Enter an integer value (negative value to quit): ");
val = inScanner.nextLine();
}
return Integer.parseInt(val);
}
public static boolean checkForValidDecimal(String value) {
int length = value.length();
int pos = 0;
boolean a = true;
while (pos < length) {
a = Character.isDigit(value.charAt(pos));
if (a == true) {
pos++;
}
else {
if (value.charAt(0) == '-') {
pos++;
}
else {
a = false;
}
}
}
return a;
}
}

You forgot to update your value after you write the binary out.
public static String decimalToBinary(int value) {
String binary = "";
int i = 0;
while (value > 0) {
i = value % 2;
value = value / 2;
if (i == 1) {
binary = binary + "1";
}
else {
binary = binary + "0";
}
}
return binary;
}

Related

Why am I getting these no suitable method found errors?

Im trying to write this class copied from my textbook. From what i understand, I copied the code exactly as it appeared, with minor changes to variable names. But when I do anything, the two lines number = getInt(Sc3, prompt); and d = getDouble(sc3, prompt); throw errors that say "no suitable method found for getInt/getDouble(Scanner, String). Why is this and what can I code to fix this? The surrounding code below.
import java.util.Scanner;
public class Console {
private static Scanner sc3 = new Scanner(System.in);
public static String getString(String prompt) {
System.out.print(prompt);
String s = sc3.next();
sc3.nextLine();
return s;
}
public static int getInt(String prompt) {
int number = 0;
boolean isValid = false;
while (isValid) {
System.out.print(prompt);
if (sc3.hasNextInt()) {
number = sc3.nextInt();
isValid = true;
}else {
System.out.println("Error! Entry must be an integer. Please try again.");
}
sc3.nextLine();
}
return number;
}
public static int getInt(String prompt, int minimum, int maximum) {
int number = 0;
boolean isValid = false;
while (!isValid) {
number = getInt(sc3, prompt);
if (number <= minimum) {
System.out.println("Error. User entry nust be greater than" + " " + minimum + " " + ".");
} else if (number >= maximum) {
System.out.println("Error. User entry must be less than" + " " + maximum + " " + ".");
} else {
isValid = true;
}
}
return number;
}
public static double getDouble(String prompt) {
double d = 0;
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
if (sc3.hasNextDouble()) {
d = sc3.nextDouble();
isValid = true;
} else {
System.out.println("Error. Invalid number. Try again.");
}
sc3.nextLine();
}
return d;
}
public static double getDouble(String prompt, double minimum, double maximum) {
double d = 0;
boolean isValid = false;
while (!isValid) {
d = getDouble(sc3, prompt);
if (d <= minimum) {
System.out.println("Error. Number must be greater than" + minimum + ".");
}else if (d >= maximum) {
System.out.println("Error. Number must be less than" + maximum + ".");
}else {
isValid = true;
}
return d;
}
}
}
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists
from here
So you are missing the getInt(Scanner Sc3, String prompt) and getDouble(Scanner sc3, String prompt) methods.

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

Number guesser program throwing exceptions Java

I am trying to add exceptions to a program i've already wrote. I need to write exceptions when the user tries to cheat on a number guess program for the higher and lower methods as well as add a try/catch on the game to display the error. I almost have it written correctly but and exception is thrown right before the last possible outcome. Attached is the class file i wrote along with the program to run the game.
Here is my class for the number guesser logic
public class NumberGuesser {
private int min, max, midpoint, origMin, origMax;
public NumberGuesser()
{
min = 1;
max = 100;
}
public NumberGuesser(int lowerBound, int upperBound)
{
min = lowerBound;
max = upperBound;
origMin = lowerBound;
origMax = upperBound;
}
public void setMin(int value)
{
min = value;
}
public void setMax(int value)
{
max = value;
}
public int getMin()
{
return min;
}
public int getMax()
{
return max;
}
public void higher()
{
min = getCurrentGuess() + 1;
if (min == max)
{
throw new IllegalStateException("No more possible outcomes");
}
}
public void lower()
{
max = getCurrentGuess() -1;
if (max == min)
{
throw new IllegalStateException("No more possible outcomes");
}
}
public int getCurrentGuess()
{
midpoint = (max + min) /2;
return midpoint;
}
public void reset()
{
min = origMin;
max = origMax;
}
}
Here is the program that runs the game.
import java.util.*;
public class GuessingProgram {
public static void main(String[] args) {
do
{
playOneGame();
}
while (shouldPlayAgain());
}
public static void playOneGame()
{
char input = 0;
Scanner keyboard = new Scanner(System.in);
NumberGuesser game = new NumberGuesser(1,100);
System.out.println("NUMBER GUESSER GAME");
System.out.println("-------------------");
System.out.println("Think of a number between 1 and 100");
while (input != 'c')
{
try
{
System.out.print("Is your number " + game.getCurrentGuess() + "?" +
" (h/l/c): ");
input = keyboard.next().charAt(0);
if (input == 'h' || input == 'H')
game.higher();
else if (input == 'l' || input == 'L')
game.lower();
else if (input == 'c' || input == 'C')
game.reset();
}
catch(IllegalStateException e)
{
System.out.println("Invalid input, You are cheating!!!");
}
}
}
public static boolean shouldPlayAgain()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Great! Do you want to play again? (y/n): ");
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("y"))
return true;
else
return false;
}
}
Here is my output and the number its supposed to guess is 77
NUMBER GUESSER GAME
Think of a number between 1 and 100
Is your number 50? (h/l/c): h
Is your number 75? (h/l/c): h
Is your number 88? (h/l/c): l
Is your number 81? (h/l/c): l
Is your number 78? (h/l/c): l
Is your number 76? (h/l/c): h
Invalid input, You are cheating!!!
Is your number 77? (h/l/c):
If min and max reach the same value, that means you've found the correct value. I think you want to throw illegalStateException if you say the number is higher/lower after you found the correct value, it is, max < min.

Credit card type and validation

I would like to run a program that can determine the validation and type of credit card number based of number entered. Compiler shows notification that there is an error in my coding but I cannot detect where is it. The program is also cannot be run. Below is the coding,
import java.util.*;
public class CreditCard {
public static void main(String args[]) {
String CType;(String number) {
if (number.startsWith("4"))
return "Visa";
else if (number.startsWith("5"))
return "MasterCard";
else if (number.startsWith("6"))
return "Discover";
else if (number.startsWith("37"))
return "American Express";
else
return "Unknown type";
};
Scanner input = new Scanner(System.in);
System.out.println("Enter a credit card number: ");
long number = input.nextLong();
long total = sumOfEvenPlaces(number) + (sumOfOddPlaces(number)*2);
if (isValid(total)) {
System.out.println("The "+CType+" card number is valid");
} else {
System.out.println("The "+CType+" card number is invalid.");
}
}
public static boolean isValid(long total) {
if (total % 10 != 0) {
} else {
return true;
}
return false;
}
public static int sumOfEvenPlaces(long number) {
int sum = 0;
int remainder;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
public static int getDigit(int number) {
if (number > 9) {
return (number % 10 + number / 10);
}
return number;
}
public static int sumOfOddPlaces(long number) {
int sum = 0;
int remainder;
number /= 10;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
}
I do card type detection with an enum:
package com.gabrielbauman.gist;
import java.util.regex.Pattern;
public enum CardType {
UNKNOWN,
VISA("^4[0-9]{12}(?:[0-9]{3}){0,2}$"),
MASTERCARD("^(?:5[1-5]|2(?!2([01]|20)|7(2[1-9]|3))[2-7])\\d{14}$"),
AMERICAN_EXPRESS("^3[47][0-9]{13}$"),
DINERS_CLUB("^3(?:0[0-5]\\d|095|6\\d{0,2}|[89]\\d{2})\\d{12,15}$"),
DISCOVER("^6(?:011|[45][0-9]{2})[0-9]{12}$"),
JCB("^(?:2131|1800|35\\d{3})\\d{11}$"),
CHINA_UNION_PAY("^62[0-9]{14,17}$");
private Pattern pattern;
CardType() {
this.pattern = null;
}
CardType(String pattern) {
this.pattern = Pattern.compile(pattern);
}
public static CardType detect(String cardNumber) {
for (CardType cardType : CardType.values()) {
if (null == cardType.pattern) continue;
if (cardType.pattern.matcher(cardNumber).matches()) return cardType;
}
return UNKNOWN;
}
}
You can then do CardType.detect("cardnumbergoeshere") and you'll get back CardType.VISA, etc.
There's a unit test over at the gist.
For validation, I have:
public boolean isValid(String cardNumber) {
int sum = 0;
boolean alternate = false;
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(cardNumber.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
That should do it.
Edit: fixed escape characters in DINERS_CLUB
This may be more along the lines of what you're trying to do:
public static void main(final String args[])
{
String cType = null;
System.out.println("Enter a credit card number: ");
final Scanner input = new Scanner(System.in);
final String cardNumber = input.next();
if (cardNumber.startsWith("4"))
{
cType = "Visa";
}
else if (cardNumber.startsWith("5"))
{
cType = "MasterCard";
}
else if (cardNumber.startsWith("6"))
{
cType = "Discover";
}
else if (cardNumber.startsWith("37"))
{
cType = "American Express";
}
else
{
cType = "Unknown type";
}
final long total = sumOfEvenPlaces(Long.valueOf(cardNumber)) + (sumOfOddPlaces(Long.valueOf(cardNumber)) * 2);
if (isValid(total))
{
System.out.println("The " + cType + " card number is valid");
}
else
{
System.out.println("The " + cType + " card number is invalid.");
}
}
On a stylistic note, CType should start with a lower case letter (e.g. cType). You'll have to experiment with the use of Scanner as well as I'm not sure my implementation will do what you're looking for.

Why is my program crashing (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;
}

Categories

Resources