Method that counts amount of chars - java

I've created a bank. I need this "Luhn" class to validate the social security number. The problem is, when the user inputs a number that's 1-9 digits, the program just stops. I want it to show a message like "Invalid input. Please try again". How do i do that?
package bank6;
import java.util.Scanner;
public class Luhn {
public static boolean checkLogin(String custPnr) {
int length = custPnr.length();
int sum = 0;
int pos = length-1;
for (int i = 1; i<=10; i++, pos--){
char tmp = custPnr.charAt(pos);
int num = Integer.parseInt(String.valueOf(tmp));
int produkt;
if (i % 2 != 0){
produkt = num * 1;
}else {
produkt = num * 2;
}
if ( produkt > 9 )
produkt -= 9;
sum += produkt;
}
boolean korrekt = (sum % 10) == 0;
if (korrekt){
System.out.println("Correct");
return true;
}else {
System.out.println("Invalid");
return false;
}
}
public static void main(String[] args) {
String pnr;
System.out.println("Welcome customer. Please login by using your "+ "birthdate (yymmddxxxx)");
Scanner input = new Scanner(System.in);
pnr = input.nextLine();
checkLogin(pnr);
}
}
EDIT;
Okay, i edited my code. But i still get errors. I Think im kind of retarded when i comes to coding. Im about to eat my own head soon.
I understand why i am getting infinite recurse but not how to fix it. And how do i fix so i dont have to print out the message to the customer two times?
i am trying to build a bank. To even get logged in to watch your accounts and so on you need to validate you're a Swedish citizen by typing in a Swedish social security number. This is a class were the validation of code is. The codes mission is to validate the security number. If the number is fake, the code will give an "false" return (bottom of code) and "true" return if its true. The problem i had in the start was that if someone typed in a 1-9 digit number then it would just crash. I wanted it to give a "Sorry, invalid input. Please try again" and then the user was supposed to be taken back to the login and try again.
I couldn't run the code from the main class so i had to make a main at the bottom of the page just to be able to fix the above problem.
That's were im at now.
package bank6;
import java.util.Scanner;
public class Luhn {
public static boolean checkLogin(String custPnr) {
String pnr;
System.out.println("Welcome customer. Please login by using your "
+ "birthdate (yymmddxxxx)");
Scanner input = new Scanner(System.in);
pnr = input.nextLine();
do {
System.out.println("Sorry, invalid input. Try again.");
checkLogin(pnr);
} while (pnr.length() != 10);
int length = custPnr.length();
int sum = 0;
int pos = length - 1;
for (int i = 1; i <= length; i++, pos--) {
char tmp = custPnr.charAt(pos);
int num = Integer.parseInt(String.valueOf(tmp));
int produkt;
if (i % 2 != 0) {
produkt = num * 1;
} else {
produkt = num * 2;
}
if (produkt > 9) {
produkt -= 9;
}
sum += produkt;
}
boolean korrekt = (sum % 10) == 0;
if (korrekt) {
System.out.println("Correct");
return true;
} else {
System.out.println("Invalid");
return false;
}
}
public static void main(String[] args) {
String pnr;
System.out.println("Welcome customer. Please login by using your "
+ "birthdate (yymmddxxxx)");
Scanner input = new Scanner(System.in);
pnr = input.nextLine();
checkLogin(pnr);
}
}

When you get the use input, just use an if-statement to check the length.
Example
String str = input.nextLine();
if(str.length() > 9){
// Print error message
}else{
checkLogin(str);
}
You could use a do-while loop and use str.length() > 9 as the condition so that it loops until a valid string of characters is entered. If you haven't used do-while loops, try googling them!

The problem is here:
for (int i = 1; i<=10; i++, pos--)
You always loop from 1 to 10 as if there were 10 characters. If the user inputs a String smaller than 10 characters, your "pos" will go beyond 0, and you will get a StringIndexOutOfBoundsException here:
char tmp = custPnr.charAt(pos);
Instead you should try:
for (int i = 1; i<=length; i++, pos--)
To check the length of the input before you perform the check:
String str = input.nextLine();
if(str.length() != 10){
System.out.println("Invalid input. Please try again");
return false;
}else{
checkLogin(str);
}

Related

palindrome program not working as expected

I know it's very puny thing for experts here but I want to check why my palindrome program is not working as expected, it shows as palindrome to every number or string i enter, can you please look into it where the issue is, please.
actually i'm trying to create this program on my own and not checking any ready made method for it so asking here. please help.
here's my program
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String k = sc.next();
int s = k.length()/2;
boolean b = true;
while(s>0){
for (int i = 0; i<=s; i++) {
if(k.charAt(i)==k.charAt(s)){
b = true;
}
}
if (b)
s--;
else
System.out.println("exit");
}
if(b)
System.out.println("palindrome");
}
}
s is the midpoint, and you are modifying it in your loop. Also, you never set b to false in any condition. Fixing those two bugs, should give you something like
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String k = sc.next();
int s = k.length() / 2;
boolean b = true; // <-- Default to true
for (int i = 0; i <= s; i++) { // <-- Only need one loop.
if (k.charAt(i) != k.charAt(k.length() - i - 1)) {
b = false; // <-- Only need to update when it isn't a palindrome.
break; // <-- terminate the loop.
}
}
if (b) { // <-- Use braces. Even when optional.
System.out.println("palindrome");
}
You might be better off writing a simple method to do the check and call that method with your input.
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String str = sc.next();
System.out.printf("'%s' %s%n", str, (isPalindrome(str) ? "is " : "is not ") + "a palindrome.");
For inputs of radar and abcdcbc prints
'radar' is a palindrome.
'abcdcbc' is not a palindrome.
The method
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len / 2; i++) {
if (str.charAt(i) != str.charAt(len - i - 1)) {
return false; // return as soon as characters don't match
}
}
// if the program gets this far, the string must be a palindrome
return true;
}

How to split a string up and save it to a variable if it is valid?

I'm having some problems splitting a string that is read in from an input file, making sure it's valid, then saving it to a variable.
Let's say this is the first string:
12345 5 59.28
I would want to split the 12345, 5, and 59.28.
After verifying that they are the correct format ( 00000-99999, 0-5, 000.00 0 100.00 ), I would then assign it to a variable.
My main two obstacles are that I CANNOT use arrays in this program, so I'm not sure how to split the string. I have tried just pulling each section as an int, but that doesn't seem to work.
My other problem is that I'm not sure how to validate it. Would I be using something like this:
//Assuming I have a scanner set up and a class, method declared
//Declare variables
int numbers;
int studentID;
while(fileInput.hasNext())
{
numbers = fileInput.nextInt(); //Not sure how to pull a part of the string
}
//Used to validate that it is within the range
if(numbers < 00000 || numbers > 99999)
{
studentID = numbers;
}
I am a beginner at Java so please do excuse my confusion.
If you know what the structure of the file is, for example if it's always formatted like this:
int int double
Then you can simply callnextInt(), nextInt(), and then nextDouble() to parse the data from it that way.
Maybe something like this
do
{
num1 = scanner.nextInt();
num2 = scanner.nextInt();
num3 = scanner.nextDouble();
} while (scanner.hasNextInt());
And do that in order to collect all of your data, but you'll likely need lots of variables if you have any substantial amount of data you're reading in
Or if there's bad data sometimes with it's correct data immediately after it you could so something like this to skip over the bad one, even though it's not very pretty
do
{
if (scanner.hasNextInt())
{
num1 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num1 = scanner.nextInt();
}
if (scanner.hasNextInt())
{
num2 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num2 = scanner.nextInt();
}
if (scanner.hasNextDouble())
{
num3 = scanner.nextDouble();
}
else
{
scanner.next() // move past whatever bad data there was
num3 = scanner.nextDouble();
}
} while (scanner.hasNext());
I think your teachers give this assignment to practice your if-else condition or switch statement and for loop(fundamental) skills.
Here what I did, this may be not completely match with your assignment question but using this you can get complete idea and think of a way to reduce this. Hey! because of we are not here to do your assignment. you have to tackle with your problem and get familiar with those.
Try to understand these, do changes look what happen:
public static void main(String[] args) {
Scanner fileInput = new Scanner(System.in);
//Declare variables
String numbers = "";
String firstNum = "";
String secondNum = "";
String thirdNum = "";
int studentID = 0;
int secondDigit = 0;
double thirdDigit = 0;
System.out.print("Input: ");
numbers = fileInput.nextLine();
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
firstIndex = numbers.indexOf(" ");
if(firstIndex <= 4){
System.out.println("Number should be 5");
}else{
firstNum = numbers.substring(0, firstIndex);
numbers = numbers.substring(firstIndex+1);
studentID = Integer.parseInt(firstNum);
if(studentID > 0 && studentID < 99999){
System.out.println("First num: " +firstNum);
}else{
System.out.println("first digits not in a range ");
}
}
secondIndex = numbers.indexOf(" ");
if(secondIndex == 0){
System.out.println("no number");
}else{
secondNum = numbers.substring(0, secondIndex);
numbers = numbers.substring(secondIndex+1);
secondDigit = Integer.parseInt(secondNum);
if(secondDigit >= 0 && secondDigit <= 5){
System.out.println("Second num: " +secondNum);
}else{
System.out.println("second digit not in a range ");
}
}
thirdIndex = numbers.length();
if(thirdIndex < 3){
System.out.println("3 numbers should be there");
}else{
thirdNum = numbers.substring(0, thirdIndex);
thirdDigit = Double.parseDouble(thirdNum);
if(thirdDigit >= 0 && thirdDigit <= 100){
System.out.println("third num: " +thirdNum);
}else{
System.out.println("third digit not in a range ");
}
}
}
I'm not going to explain this also. You have to try, if you have any problem after tackling with this code. ask any question in comment.
Hope this will help!
Try this. Invalid formats will throw an exception during the next method call.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner("12345 5 59.28");
in.useDelimiter(" "); // reads per space
String next = in.next("\\d{5}"); // reads next 5 digits
int numbers = Integer.valueOf(next);
System.out.println(numbers);
next = in.next("\\d{1}"); // reads next 1 digit
int studentId = Integer.valueOf(next);
System.out.println(studentId);
next = in.next("\\d{2}\\.\\d{2}"); // reads next a decimal with two digits before and after point
float floatingNumbers = Float.valueOf(next);
System.out.println(floatingNumbers);
}
}
<script src="//repl.it/embed/IWzC/0.js"></script>

Validate multiple inputs to an array in java

I have a HOMEWORK assignment that involves users inputs.
I want to ask the user for three integer inputs in the range 1-7 and store them in an array.
What I have so far seems to validate properly if all inputs are over 7 and rules out strings etc inputs and but still allows for a single input to be over 7.
Any help is appreciated.
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
while(!valid)
{
System.out.println("enter three numbers: ");
if(in.hasNextInt())
{
for(int i = 0; i< inputRange.length; i++)
{
inputRange[i] = in.nextInt();
if(inputRange[i] >= 1 && inputRange[i] <= 9){
valid = true;
}
}
}else{
in.next();
}
}
Your logic is fine, but you need to restart valid to false again each time user is going to enter a new digit.
Here's how you can validate user input to be between 1-9 with a do-while using your same logic just a little bit different.
Also next time be sure to post a valid MCVE and not just "snippets" (it should include a main method and imports)
import java.util.Scanner;
public class ValidationOfNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
int counter = 0;
int number = 0;
System.out.println("Enter 3 digits between 1-9"); //Ask for digits, numbers can have multiple digits, while digits are numbers from 0-9
for (int i = 0; i < inputRange.length; i++) {
valid = false; //Restart "valid" variable for each new user input
do {
number = in.nextInt();
if (number >= 1 && number <= 9) {
valid = true; //If valid, it will exit do-while
} else {
System.out.println("Enter a valid digit between 1-9");
}
} while (!valid);
inputRange[i] = number; //We know it's valid because it went out of do-while, so we can now store it in the array
}
for (int i = 0; i < inputRange.length; i++) {
System.out.println(inputRange[i]);
}
}
}
Here is the code
Scanner in = new Scanner(System.in);
int count = 0;
int data[] = new int[3];
while(count < 3) {
if(in.hasNextInt()) {
int val = in.nextInt();
if(val>=1 && val <=7) {
data[count] = val;
count++;
}
}
else {
in.next();
}
}

String index out of range inside of a method: Java

I was writing some code for my class and I ran into this error, String index out of range. I checked to see if it might be the string = null but that's not the case. I'm guessing it has to do with my if statement in the method but I couldn't find how to fix it anywhere. Any help is appreciated, thank you very much!
import java.util.*;
public class Occurences {
public static void main(String[] args) {
int check = 0;
char characterInput = ' ';
do {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string: ");
String input = scan.next();
System.out.println("Enter a character to find it's occurence in the string: ");
characterInput = scan.next().charAt(0);
int i = count(input, characterInput);
System.out.println(characterInput + ", is in " + input + ", " + i + " times.");
System.out.println("To continue enter any number, to exit enter -1: ");
check = scan.nextInt();
} while (check != -1);
}
public static int count(String input, char characterInput) {
int cnt = 0;
int j = input.length();
while (j > 0) {
if (input.charAt(j) == characterInput) {
cnt += 1;
}
j--;
}
return cnt;
}
}
The error happens on line 21: int j = input.length(), as others mentioned in the comments, java, and most programming languages, index strings and array types by zero-indexing - starting from zero. So you have to either 1) start counting at 0 or 2) stop counting at one-less-than the length of the string(array), which is why line 21 needs to be either:
int j = input.length()-1;
or as you solved it using method 1:
setting int j=0;

Printing a Rectangle in Java with limits and IF statement that isn't working

I am trying to create a program that takes user input and makes a rectangle. The user input to numbers for length and width and another symbol or character to fill in the rectangle. That all works fine. My code works for creating a rectangle of any size but I need limit If the no of rows or cols is less than or equal to zero or more than 50 it needs to print out "error in input".
This is the code I have and I am currently trying to define it with if statement and it keeps print the state "error in input and the rectangle. Any help would be appreciated or another method to achieve the same thing.
import java.util.Scanner;
public class Rectangle
{
public static void main(String[] args)
{
int length;
int width;
String symbol;
char symbolz;
int xLength;
int yWidth;
Scanner input = new Scanner(System.in);
while(input.hasNext()){
{ width = input.nextInt();
length = input.nextInt();
symbol = input.next();
symbolz = symbol.charAt(0);
if (length<=0||length>50||width<=0||width>50){
}
System.out.print("error in input");{
{for (yWidth = 1; yWidth <= width; yWidth++){
for (xLength = 1; xLength <= length; xLength++) {
System.out.print(symbolz);
}
System.out.println(" ");
}
for(yWidth = 1; yWidth >= width; yWidth--){
for (xLength = 1; xLength >= length; xLength--){
System.out.print(symbolz);
}
System.out.println(" ");
}
}
}
}
}
}}
Edited: switched to if statement but still am having trouble because it keeps inserting "error in user input" in all things typed and also prints the rectangle when it isn't supposed to.
So far I have tried to get the If statement to work and it keeps doing the same thing where it keeps print "error in user input" on inputs that are out side the range but it also prints the rectangle after which it shouldn't do. Any guidance?
The construct is called a do-while, and the general format is:
do {
// statements
} while (condition);
Your do loop is missing the while (condition) which indicates when the loop should stop.
It's essentially a while loop, with the difference being that with do-while, condition is tested at the end of the loop, where with a while loop, it's tested at the start, so a do-while will always execute the loop at least once.
I got it to work with a if and continue statement.
import java.util.Scanner;
public class Rectangle
{
public static void main(String[] args)
{
int length;
int width;
String symbol;
char symbolz;
int xLength;
int yWidth;
Scanner input = new Scanner(System.in);
while(input.hasNext()){
{ width = input.nextInt();
length = input.nextInt();
symbol = input.next();
symbolz = symbol.charAt(0);
if (length<=0||length>50||width<=0||width>50){
System.out.print("error in input");
System.out.println();
continue;}
{
for (yWidth = 1; yWidth <= width; yWidth++){
for (xLength = 1; xLength <= length; xLength++) {
System.out.print(symbolz);
}
System.out.println(" ");
}
for(yWidth = 1; yWidth >= width; yWidth--){
for (xLength = 1; xLength >= length; xLength--){
System.out.print(symbolz);
}
System.out.print(" ");
}
}
}
}
}
}
Error is here :
if (length<=0||length>50||width<=0||width>50){
} // --> Error: if input outside range then we have to use continue or exit.
System.out.print("error in input");{ // Message must be in previous if
use This:
if((length<=0 || length >50) || (width<=0 || width>50))
{
System.out.println("Error in input");
}
Hope this may solve your problem.

Categories