I am trying to convert the input of a Int directly to a String.
I am also trying to make it so the program will find the correct number in a credit card sequence to make it correct.
For example if I input a incorrect credit card number, the program finds a way to change the numbers so it becomes correct.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input a credit card number to validate");
String cc = in.nextLine();
validateCreditCardNumber(cc);
String convertedCC = (cc);
}
private static void validateCreditCardNumber(String str) {
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum += ints[i];
}
if (sum % 10 == 0) {
System.out.println(str + " is a valid credit card number");
} else {
System.out.println(str + " is an invalid credit card number");
}
}
That is all my code, but what i am trying to fix is when I initialize cc, i can convert to a string to be later used.
My issues:
int to string has been fixed,
converting to correct CC number has not been fixed.
Can you just get it as a string directly?
String cc = in.nextLine();
Use following code instead of int cc = in.nextInt();
String cc = in.next();
You never use the int version of the scanned input. Instead of making cc an int then converting to a string, just initially make it a string... something like this:
String cc = in.nextLine();
Related
I am creating a program that generates a random password and asks the user to guess the generated password.
The problem I'm facing now is how to compare the generated password to the inputted password
My program compares the length of both passwords, but I don't know any possible way to compare both passwords to see if they're the same or not
The program has to compare both passwords and after three attempts, the program has to output the generated password
The code below is my program
final static Scanner in = new Scanner(System.in);
public static String method(int len){
String ASCII = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z";
int count =0;
int rand;
System.out.println("Guess the generated password");
String key = in.nextLine();
for(int i=0;i<key.length();i++){
count++;
}
SecureRandom sr = new SecureRandom();
StringBuilder sb = new StringBuilder();
for(int i =0;i<len;i++){
rand= sr.nextInt(ASCII.length());
sb.append(ASCII.charAt(rand));
}
for(int i=0;i<3;i++){
if(len!=count){
System.out.println("The length of the random generated password is "+ len+ " and the length of the password inserted is " + count);
System.out.println("The length of the generated password and the length of the inserted password varies. Please try again...");
System.out.println("Guess the generated password again");
key = in.nextLine();
}
}
return sb.toString();
}
public static void main(String[] args) {
Random r = new Random();
int len;
len = r.nextInt(1, 8);
System.out.println("length :" + len);
System.out.println(method( len));
}
}
You have made some strides in your coding since this post was originally placed. Based on your newest code shown below (from the post you deleted):
final static Scanner in = new Scanner(System.in);
public static String method(int len) {
//Create a variable to hold the ASCII character
String ASCII = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z";
int count = 0;
int rand;
System.out.println("Guess the generated password");
String key = in .nextLine();
for (int i = 0; i < key.length(); i++) {
count++;
}
SecureRandom sr = new SecureRandom();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
rand = sr.nextInt(ASCII.length());
sb.append(ASCII.charAt(rand));
}
for (int i = 1; i < 3; i++) {
while (len != key.length()) {
System.out.println("Length do not correspond please try again");
key = in .nextLine();
}
if (len == key.length() && !sb.toString().equals(key)) {
System.out.println("Length correspond but passwords differ, Try again");
key = in .nextLine();
}
}
System.out.print("The correct password is: ");
return sb.toString();
}
public static void main(String args[]) {
// Create a random length generator
Random r = new Random();
int len;
len = r.nextInt(1, 7);
System.out.println("lungezza :" + len);
System.out.println(method(len));
}
When generating a random number within a specific range like 1 inclusive to 7 inclusive then do it this way:
// int len = rand.nextInt((max - min) + 1) + min; thus...
int len = new Random().nextInt((7 - 1) + 1) + 1;
Don't add a bunch of whitespaces in your ASCII String variable. Consider not having whitespaces at all or if you have to, just provide one between the Upper and lower letters, for example:
String ASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz";
I say this because potentially, there is a good chance your random password generation could create a password that is all whitespaces which really isn't a password at all.
Also, I know your compiler isn't complaining but readers of your code will....consider using proper naming conventions for your variables, etc. ASCII should be ascii or even aSCII unless it is going to be a class Field variable which it is not. It is currently considered a method local variable. You actually did this correctly in this older post.
You can not guess an auto-generated password if that auto-generated password has not been generated yet. The code which auto-generates the password to guess is currently after the first prompt which asks you to supply what it is.
Move the code that generates the password above the code that asks the first prompt of what that password might be, for example:
//Create a variable to hold the ASCII characters
String ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz";
// Generate the secret password to guess...
SecureRandom sr = new SecureRandom();
StringBuilder sb = new StringBuilder("");
int rand;
for (int i = 0; i < len; i++) {
rand = sr.nextInt(ascii.length());
sb.append(ascii.charAt(rand));
}
// Guess the password...
int count = 0;
System.out.print("Guess the generated password: -> ");
String key = in .nextLine();
for (int i = 0; i < key.length(); i++) {
count++;
}
This for loop under the first Guess prompt:
int count = 0;
System.out.print("Guess the generated password: -> ");
String key = in.nextLine();
for (int i = 0; i < key.length(); i++) {
count++;
}
is not required. All it does is count the number of characters contained within the first password guess. Ironically, you already know this by just using the key.length() method. You don't use the count variable for anything anyways so you may as well just get rid of all that:
// Guess the password (3 guesses)...
System.out.print("Guess the generated password: -> ");
String key = in .nextLine();
for (int i = 1; i < 3; i++) {
while (len != key.length()) {
System.out.println("Lengths do not correspond please try again");
key = in .nextLine();
}
if (len == key.length() && !sb.toString().equals(key)) {
System.out.println("Lengths correspond but passwords differ, Try again");
key = in .nextLine();
}
}
System.out.print("The correct password is: ");
return sb.toString();
In reality, you only need one prompt and it's always nice to validate the User's input. Here is an alternative way to do this:
private final static Scanner in = new Scanner(System.in);
private static int numberOfGuessesAllowed = 3;
private static boolean correct = false;
public static void main(String args[]) {
// Create a random length generator
Random r = new Random();
int len = r.nextInt((7 - 1) + 1) + 1;
System.out.println("Password to guess contains " + len + " characters.");
System.out.println("You have " + numberOfGuessesAllowed + " attempts to guess it right!");
System.out.println(method(len));
}
public static String method(int len) {
//Create a variable to hold the ASCII characters
String ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz";
// Generate the secret password to guess...
SecureRandom sr = new SecureRandom();
StringBuilder sb = new StringBuilder("");
int rand;
for (int i = 0; i < len; i++) {
rand = sr.nextInt(ascii.length());
sb.append(ascii.charAt(rand));
}
String secretPassword = sb.toString();
// Guess the password...
String key = "";
while (key.isEmpty() && numberOfGuessesAllowed > 0) {
System.out.print("Guess the generated password (q to quit): -> ");
key = in .nextLine().trim();
if (key.equalsIgnoreCase("q")) {
return "Quitting! Bye-Bye.";
}
if (key.isEmpty()) {
System.out.println("Invalid Entry! Try again...\n");
}
else if (secretPassword.equals(key)) {
correct = true;
break;
}
else if (len != key.length()) {
numberOfGuessesAllowed--;
System.out.println("Lengths do not correspond! Please try again.\n");
key = "";
}
else if (len == key.length() && !secretPassword.equals(key)) {
numberOfGuessesAllowed--;
System.out.println("Lengths correspond but passwords differ, Try again\n");
key = "";
}
}
if (correct) {
System.out.print("You guessed it! The password is: ");
}
else {
System.out.print("You couldn't do it! The correct password is: ");
}
return secretPassword;
}
I know there are already questions asking something similar to my question, but despite reading those, they don't quite do what I want.
I am creating a code that takes a users input of a number between 0-100 (inclusive). Whatever the number, it will print all the numbers leading up to that number and that number
EX: user input = 25
output = 012345678910111213141516171819202122232425
I have that part working. Now I am supposed to use that string and create two new strings, one for only the odd and the other one for the even numbers.
EX: user input = 25
output: odd numbers: 135791113151719212325 & even numbers = 024681012141618202224
Here is my code so far:
import java.util.Scanner;
public class OddAndEven{
public String quantityToString() {
Scanner number = new Scanner(System.in);
int n = number.nextInt();
String allNums = "";
if ((n >= 0) && (n <= 100)) {
for (int i = 0;i <= n; ++i)
allNums = allNums + i;
return allNums;
}
else {
return "";
}
}
public void oddAndEvenNumbers(int num) {//Start of second method
String allNums = ""; //String that quantityToString returns
String odd = "";
String even = "";
if ((num >= 0) && (num < 10)) { //Looks at only single digit numbers
for (int i = 0; i <= allNums.length(); i++) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) { //trying to get the allNums string to be broken into individual numbers to evaluate
even = even + allNums.charAt(i); //adding the even numbers of the string
}
else {
odd = odd + allNums.charAt(i);
}
}
}
else { //supposed to handle numbers with double digits
for (int i = 10; i <= allNums.length(); i = i + 2) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) {
even = even + allNums.charAt(i);
}
else {
odd = odd + allNums.charAt(i);
}
}
}
System.out.println("Odd Numbers: " + odd);
System.out.println("Even Numbers: " + even);
}
public static void main(String[] args) {
System.out.println(new OddAndEven().quantityToString());
//System.out.println(new OddAndEven().oddAndEvenNumbers(allNums));
//Testing
OddAndEven obj = new OddAndEven();
System.out.println("Testing n = 5");
obj.oddAndEvenNumbers(5);
System.out.println("Testing n = 99");
obj.oddAndEvenNumbers(99);
I know my problem is at the part when its supposed to take the string apart and evaluate the individual numbers, but I don't know what to do. (I've also tried substring() & trim()) Also I have not learned how to use arrays yet, so that is why I did not try to use an array.
I think you can make it that way:
int x = 20;
StringBuilder evenNumberStringBuilder = new StringBuilder();
StringBuilder oddNumberStringBuilder = new StringBuilder();
for(int i =0 ; i<x+1; i++){
if(i % 2 == 0)evenNumberStringBuilder.append(i);
else oddNumberStringBuilder.append(i);
}
System.out.println(evenNumberStringBuilder);
System.out.println(oddNumberStringBuilder);
Output:
02468101214161820
135791113151719
you are already taking the input as integer, so don't work with strings. I recommend that to use this loop;
Scanner number = new Scanner(System.in);
System.out.print("Even Numbers: ");
for (int i = 0; i <= number; i=i+2) {
System.out.print(i);
}
System.out.println("");
System.out.print("Odd Numbers: ");
for (int i = 1; i <= number; i=i+2) {
System.out.print(i);
}
You can simply evaluate numbers while storing them in an allnumbers string, here's a functioning code:
int x = 23; //user input
String s=""; //contains all numbers from 0 to userinput
String odd =""; //contains all odd numbers from 0 to userinput
String even = ""; //contains all even numbers from 0 to userinput
for(int i = 0 ; i< x+1 ; i++){
s += i;
if(i%2==0) //if i is an even number
even += i;
else //if i is an odd number
odd += i;
}
System.out.println(s); //displaying all numbers from 0 to user input
System.out.println(odd); //displaying odd numbers from 0 to user input
System.out.println(even); //displaying even numbers from 0 to user input
This is the problem wherein, we will subtract two numbers using 9's complement.
import java.io.*;
public class NinesComplement {
public static void main(String[] args)throws java.io.IOException {
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
while (true) {
System.out.print("Enter Minuend: ");
int min = Integer.parseInt(br.readLine());
System.out.print("Enter Subtrahend: ");
String sub = br.readLine();
int max = Integer.toString(min).length();
for (int i = 0; sub.length() < max; i++) {
sub = 0 + sub;
}
String [] subArr = sub.split("");
int[] num = new int[subArr.length];
for (int i = 0; i < subArr.length; i++) {
num[i] = Integer.parseInt(subArr[i]);
}
int[] n = new int[num.length];
for (int i = 0; i < num.length; i++) {
for (int ii = 0; num[i] < 9; ii++) {
num[i]++;
n[i]++;
}
}
String str = "";
for (int i = 0; i < num.length; i++) {
str += Integer.parseInt(Integer.toString(n[i]));
}
int add = Integer.parseInt(str);
String ans = Integer.toString(min + add);
if (ans.length() > max) {
String temp1 = ans.substring(0, 1);
String temp2 = ans.substring(1, ans.length());
int fin = Integer.parseInt(temp2) + Integer.parseInt(temp1);
System.out.println("Answer: " + fin);
} else if (ans.startsWith("9") && ans.endsWith("9")) {
System.out.println("Answer: 0");
}
System.out.print("Do you want to try again? \n[y][n]: ");
String choice = br.readLine();
if (choice.equals("n")) {
System.out.println("Thank you!!!");
System.exit(0);
}
}
}
}
Exception in thread "main" java.lang.NumberFormatException: For input
string: ""
You're just trying to parse an empty string into a number. You should always validate user input before trying to use it :).
Add a pre-condition (just an if statement check) before using the input and print a nice message to the user if the input was bad, and just go back to waiting for more good input.
Also, to debug this issue, just make your life easier and add some print statements surrounded by quotes before you try and use the user input so you can see it.
I'm trying to make a program that checks for palindromes(words spelt the same forwards and backwards). I want to eventually compare the first char with the last char and the second char with the second to last char. I don't know what to put in the 'endingChar' string to make it check for that. Thanks.
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
String userPhrase;
Scanner sc = new Scanner(System. in );
System.out.println("Check for palindrome:");
userPhrase = sc.nextLine();
for (int i = 0; i < userPhrase.length(); i++) {
String currentChar = userPhrase.substring(i, i + 1);
String endingChar = userPhrase.substring();
System.out.println(currentChar);
System.out.println(endingChar);
// if (userPhrase.indexOf(currentChar).equalsIgnoreCase(userPhrase.indexOf()))
}
}
}
The simplest way to check for a palindrome would be to utilize StringBuilder.reverse():
boolean isPalindrome = userPhrase.equals(
new StringBuilder(userPhrase).reverse().toString());
System.out.printf("[%s] is a palindrome? %b", userPhrase, isPalindrome);
*Taken from Here, don't give me credit.
Here is some code for checking for a palindrome for integers. You could apply the logic to your code to make it work for strings as well:
// numbers to check
int numbers[] = new int[]{ 252, 54, 99, 1233, 66, 9876 };
// loop through the given numbers
for (int i = 0; i < numbers.length; i++) {
int numberToCheck = numbers[i];
int numberInReverse = 0;
int temp = 0;
// a number is a palindrome if the number is equal to it's reversed number
// reverse the number
while (numberToCheck > 0) {
temp = numberToCheck % 10;
numberToCheck = numberToCheck / 10;
numberInReverse = numberInReverse * 10 + temp;
}
if (numbers[i] == numberInReverse) {
System.out.println(numbers[i] + " is a palindrome");
}
else {
System.out.println(numbers[i] + " is NOT a palindrome");
}
You could rather use this
for(int i=0;;i++)
{
if(i>=userPhrase.length-i)
break;
if(userPhrase.charAt(i)==userPhrase.charAt(userPhrase.length-i))
{
continue;
}
System.out.println("Not matched");
}
I need to build a simple automaton for my Automata class. I am using Java and I cannot figure out for the life of me why my program keeps exiting prematurely. I've tried debugging it, having print statements everywhere to figure out where it's stopping, and although I know where it stops, I do not see anything that would make the program stop working. The stoppage happens on line 27 (Right where I SOP "Enter a string of digits...".
Knowing me it's probably something simple, but I cannot figure this one out.
import java.util.*;
public class hw1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please indicate the number of states");
int numState = input.nextInt();
int[] state = new int[numState];
boolean[] accept = new boolean[numState];
for (int i = 0; i < numState; i++) {
System.out.println("Is the state q" + (i + 1) + " a final state? (Answer 1 for yes; 0 for no)");
int finalState = input.nextInt();
if (finalState == 1)
accept[i] = true;
} // for
System.out.println("Enter the number of symbols s: ");
int numSym = input.nextInt();
int[][] next = new int[numState][numSym];
for (int i = 0; i < numState; i++) {
for (int j = 0; j < numSym; j++) {
System.out.println("What is the number for the next state for q" + i + " when it gets symbol " + j);
next[i][j] = input.nextInt();
}//nested for
}//for
String digits = input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
int[] digitArray = new int[digits.length()];
for (int i = 0; i < digits.length(); i++) {
digitArray[i] = digits.charAt(i);
}
for (int i = 0; i < digits.length(); i++) {
System.out.print(digitArray[i] + " ,");
}
System.out.println("end of program");
}// main;
}// class
Change your code to :
input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
String digits = input.nextLine();
This will get and ignore the newline character left in the stream after call to nextInt()