Java - validate strings between a range of letters [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have written a simple test program for a larger program, where I need to validate the String by a range of letters from a through to g.
The below test program should ask for a letter, then if within range of a-g print an acceptance message, else say 'oops' and ask again.

Try this Code:
public static void main(String... params) {
Scanner s = new Scanner(System.in);
Character minValue = 'a';
Character maxValue = 'g';
while (true) {
System.out.print("enter a char between a-g: ");
Character input = s.nextLine().charAt(0);
if (input >= minValue && input <= maxValue) {
System.out.println("Ok");
} else {
System.out.println("oops");
System.exit(0);
}
}
}

You can get a char from String using charAt(index).
You can check if the char is withing given range using simple comparison like c >= 'a' && c <= 'g'.

First, I don't think you should name your variable "a".
Aniways, I would validate my input like this:
a.compareTo(maxValue) >= 0 && a.compareTo(minValue) <= 0 && a.length == 1

Please try with the below code:
import java.util.Scanner;
import java.util.Scanner;
public class StringValidation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a = null;
char minValue = 'a';
char maxValue = 'g';
boolean loop = true;
int i = 0;
while (loop) {
System.out.print("enter a char between a-g: ");
a = input.nextLine();
if ((int) minValue <= (int) a.charAt(i)) {
if ((int) maxValue <= (int) a.charAt(i)) {
System.out.println("Oops! ");
System.out.print("enter a char between a-g: ");
i++;
input.nextLine();
} else {
System.out.println("Accepted");
break;
}
}
}
input.close();
}
}

Related

Number's print in its sizes [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have to Print something like this
But i face Runtime error and wrong answer
input:
153
output:
1:1
5:55555
3:333
get an integer and print each number in its size
import java.util.Scanner;
public class q9774 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entery = Integer.toString(n);
char[] E = entery.toCharArray();
for (char value : E) {
System.out.print(value + ": ");
if (value == 0) continue;
else {
for (int i = 0; i < Integer.parseInt(String.valueOf(value)); i++) {
System.out.print(value);
}
System.out.println();
}
}
}
}
Since Java-11, you can use String#repeat to repeat a string for a given number of times.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entry = Integer.toString(n);
for (char value : entry.toCharArray()) {
System.out.print(value + ": ");
System.out.println(String.valueOf(value).repeat(Character.getNumericValue(value)));
}
}
}
A sample run:
153
1: 1
5: 55555
3: 333
An alternative way to process each character can be to split the string on each character and then repeat it for number of times equal to its numeric value.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entry = Integer.toString(n);
for (String s : entry.split("")) {// Split on each character
System.out.print(s + ": ");
System.out.println(s.repeat(Integer.parseInt(s)));
}
}
}
Here is one way of doing it.
converts the int to a String and then to a char[] array
prints the character followed by itself repeated.
any character digit - '0' is a numeric value of the same quantity represented by the character. So the character '7' has the int value of '7' - '0' or 7.
int i = 153;
for (char c : Integer.toString(i).toCharArray()) {
System.out.printf("%c:%s%n", c, (c+"").repeat(c-'0'));
}
Prints
1:1
5:55555
3:333
I added a nested loop for each digit and I repeat that nested loop according to index of value in string by j <= i; condition:
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entery = Integer.toString(n);
char[] E = entery.toCharArray();
for (int i = 0; i < E.length; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(E[i]);
}
System.out.println();
}

How to determine if user's input string is read the same backwards ( palindrome ) JAVA [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
package com.jetbrains;
import java.util.Objects;
import java.util.Scanner;
public class SA {
public static void main(String[] args) {
//scanner object
Scanner input = new Scanner(System.in);
//comment
System.out.println("Please enter a line of text below:");
String letters = input.nextLine(); //User's string input
if (letters.length() < 7) {
System.out.println("The input is too short.");
}
//variables
int l = letters.length()-5; //where the last 5 characters are located in user's input string
String answer = letters.substring(l) + letters.substring(2,l) + letters.substring(0, 2); // first 2 & last 5 swapped
if (letters.length() > 7) {
System.out.println("Convert to upper cases:");
System.out.println(letters.toUpperCase());
System.out.println("Swap the first 2 characters with the last 5 characters:"); // Swap
System.out.println(answer);
System.out.println("Is it a palindrome?");
for (int i = (letters.length() - 1); i >= 0; i--) {
char backwards = (letters.charAt(i));
for (int n = letters.indexOf(0); n >= 0; n++) {
char forwards = (letters.charAt(n));
if (Objects.equals(forwards, backwards)) {
System.out.println("True");
else
System.out.println("False");
}
}
}
}
}
}
I've tried comparing my user's input by making the for-loop outputs into char variables but it always returns false. I'm not sure how to fix this last bit, I've tried doing other things but I am completely stumped. My class hasn't learned StringBuilder or StringBuffer so I cannot use them in my code. Any tips or hints would be very helpful, thank you.
I have modified your code little bit to get the correct result -
import java.util.Scanner;
public class StringAnalysis {
public static void main(String[] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Comment to the user
System.out.println("Please enter a line of text below:");
String letters = input.nextLine(); //User's string input
if (letters.length() < 7) {
System.out.println("The input is too short. No analysis to be performed.");
}
//variables
int l = letters.length() - 5; //States the index number of where the last 5 characters are located in user's input string
String answer = letters.substring(l) + letters.substring(2, l) + letters.substring(0, 2); // first 2 & last 5 swapped
if (letters.length() > 7) {
System.out.println("Analysis #1: Convert to upper cases:"); // Upper case
System.out.println(letters.toUpperCase());
System.out.println("Analysis #2: Swap the first 2 characters with the last 5 characters:"); // Swapping
System.out.println(answer);
System.out.println("Analysis #3: Is it a palindrome?");
String backwards = "";
for (int i = (letters.length() - 1); i >= 0; i--) {
backwards = backwards + letters.charAt(i);
}
if(letters.equalsIgnoreCase(backwards)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
}
You have a problem on the second loop for checking palindrome , i tried to solve it , but eventhough , it compares every backward letters to all forwards which is logically wrong , here is something better you can do :
System.out.println("Analysis #3: Is it a palindrome?");
boolean response = true;
for (int i = 0 ; i < letters.length() ; i++) {
String backwards = String.valueOf(letters.charAt(i));
String forwards = String.valueOf(letters.charAt(letters.length()-i-1));
if(!backwards.equals(forwards)) {
response = false;
}
}
System.out.println(response);

Method that counts amount of chars

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);
}

Why doesn't the following program work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I can't figure out why the following program doesn't work. Please help me where did I make a mistake. Thank you.
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
int[] numbers = new int[100];
int largestNumber = 0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
Scanner sc = new Scanner(System.in);
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
}
}
This part:
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
makes no sense. You:
test if the next thing in the input is an integer;
attempt to parse ten next tokens, assuming that they are all integers;
at the eleventh token you check whether it's another integer or "finish";
throw an exception if it's neither;
repeat everything if it's not "finish".
What you should actually do is something much, much simpler:
check next token:
if it's "finish", you're done;
if it's an integer, parse it;
otherwise throw error;
repeat this for up to 100 times;
you are done accepting input. Proceed to processing it.
I think that Scanner is unnessecarily complicated and doesn't work to much of the time. Here's how to do it the old fashioned way:
public class LargestNumber {
public static void main(String[] args) {
int largestNumber=0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while (!(line = r.readLine()).equals("finish")) {
int val = Integer.parseInt(line);
if (val > largestNumber)
largestNumber = val;
}
System.out.println("The largest number is: " + largestNumber);
}
}
For this, enter each number on a new line. I used a shorter algorithm here, which is to read one number, and if it is bigger than the maximum so far, the new number is the maximum so far
According to the doc:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
So i thing you could do this instead:
int counter = 0;
while (counter < numbers.length) {
if (sc.hasNextInt()) {
numbers[counter++] = sc.nextInt();
} else {
if (sc.hasNext("finish")) {
sc.close();
break;
} else {
System.out.println("It's neither number nor 'finish'.");
sc.next();
}
}
}
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
hope that helps

How to implement Java "Scanner" in C++?

Please have a look at the following java code
import java.util.Scanner;
public class Main
{
static int mul=1;
static String convert;
static char[] convertChar ;
static StringBuffer buffer = new StringBuffer("");
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
int number=0;
int loopValue = scan.nextInt();
//System.out.println("print: "+loopValue);
for(int i=0;i<loopValue;i++)
{
number = scan.nextInt();
// System.out.println("print: "+number);
for(int a=1;a<=number/2;a++)
{
if(number%a==0)
{
//System.out.println(a);
mul = mul*a;
//System.out.println(mul);
}
}
convert = String.valueOf(mul);
convertChar = convert.toCharArray();
if(convertChar.length>4)
{
/*System.out.print(convertChar[convertChar.length-4]);
System.out.print(convertChar[convertChar.length-3]);
System.out.print(convertChar[convertChar.length-2]);
System.out.print(convertChar[convertChar.length-1]);
System.out.println();*/
buffer.append(convertChar[convertChar.length-4]);
buffer.append(convertChar[convertChar.length-3]);
buffer.append(convertChar[convertChar.length-2]);
buffer.append(convertChar[convertChar.length-1]);
System.out.println(buffer);
}
else
{
System.out.println(mul);
}
//System.out.println(mul);
mul = 1;
}
}
}
This code is built to compute the product of positive divisors of a given number. I have used scanner here because I don't know how many inputs will be entered. That is why I can't go something like
int a, b;
cin >> a >> b
in C++. All the inputs will be inserted by a test engine, into one single like like following
6 2 4 7 8 90 3456
How can I implement the Java "Scanner" using C++ ? Is there a header file for that? Please help!
You seem to be using Scanner to read one integer at a time from the standard input stream. This is easily accomplished with the extraction operator, operator>>.
Replace this code:
Scanner scan = new Scanner(System.in);
int number=0;
int loopValue = scan.nextInt();
//System.out.println("print: "+loopValue);
for(int i=0;i<loopValue;i++)
{
number = scan.nextInt();
// System.out.println("print: "+number);
With this:
int number=0;
int loopvalue=0;
std::cin >> loopvalue;
for(int i = 0; i < loopValue; i++)
{
std::cin >> number;
You should check the value of std::cin after the >> operations to ensure that they succeeded.
Refs:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
If you use std::cin >> value; to read the value then you can only process the entire line once a new-line has been detected.
If you want to process each number as it is typed then you could use a function like:
int nextInt()
{
std::stringstream s;
while (true)
{
int c = getch();
if (c == EOF) break;
putch(c); // remove if you don't want echo
if ((c >= '0' && c <= '9') || (c == '-' && s.str().length() == 0))
s << (char)c;
else if (s.str().length() > 0)
break;
}
int value;
s >> value;
return value;
}
OK, there are probably more efficient ways to write that but it will read the input character by character until a number is encountered and will return whatever number is read when anything other than a number is encountered.
E.g. 1 2 3 4 would return 1 on the first call, 2 on the second etc.

Categories