Java program to check spanish ID letter - java

the user has to type their ID, including the letter (example 19452100G) the program has to say if the letter is correct or not. If the letter is not correct, the program will write the correct one.
Scanner sc = new Scanner(System.in);
System.out.print("Enter ID number: ");
int numID = sc.nextInt();
System.out.printf("letter corresponde %d is %c", numID, calculateLetter(numID));
sc.close();
}
private static char calculateLetter(int id){
String caracteres="TRWAGMYFPDXBNJZSQVHLCKE";
int resto = id%23;
return caracteres.charAt(resto);
}
#SuppressWarnings("unused")
private static char calcularLetraArray(int dni){
char caracteres[] = {'T','R','W','A','G','M','Y','F','P','D','X','B','N','J','Z','S','Q','V','H','L','C','K','E'};
int resto = id%23;
return caracteres[resto];
}
}

1.You are storing a String variable inside a Integer Variable.
2.Also there is no need of two methods for checking letter and correcting the letter
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter ID number: ");
String numID = sc.nextLine();
char letter_corresponde = calculateLetter(numID);
System.out.printf("letter corresponde %s is %c \n", numID, letter_corresponde);
if (numID.charAt(numID.length()-1) == letter_corresponde)
System.out.println("letter_corresponde matches no need to correct it");
else {
System.out.println("Correcting the letter_corresponde");
numID = numID.substring(0,numID.length()-1) + letter_corresponde;
System.out.println(numID);
}
}
public static char calculateLetter(String numID){
String caracteres="TRWAGMYFPDXBNJZSQVHLCKE";
int id = Integer.parseInt(numID.substring(0,numID.length()-2));
int resto = id%23;
return caracteres.charAt(resto);
}

Related

Take two user inputs and print them out with a random number at the end

package stringvars;
import java.util.Scanner;
public class ConcertID {
public static void main(String[] args) {
try (Scanner userInput = new Scanner (System.in)) {
String yourName;
System.out.print ("enter the last letter of your second name: ");
yourName = userInput.next();
String yourDOB;
System.out.print ("enter your Year Of Birth: ");
yourDOB = userInput.next();
String ConcertID;
ConcertID = yourName + " " + yourDOB;
System.out.println("your concert ID is " + ConcertID);
}
}
}
I'm trying to get the code to take the user input, add a number between 1 and 10 at the end and print it as Y18867. Currently it prints as Y 1886.
(And I've yet to figure out the math.random part.)
Let me recommend you start using the StringBuilder class to create concatenated strings. It has a better performance regarding time consuming to concatenate strings.
The following code generates the random number as well as the concertId string that you are trying to get.
public class ConcertID
{
public static void main(String[] args)
{
try (Scanner userInput = new Scanner(System.in))
{
String yourName;
System.out.print("Enter the last letter of your second name: ");
yourName = userInput.nextLine();
String yearOfBirth;
System.out.print("Enter your Year of Birth: ");
yearOfBirth = userInput.nextLine();
StringBuilder concertId = new StringBuilder();
concertId.append(yourName);
concertId.append(yearOfBirth);
concertId.append(generateNumber());
System.out.println(concertId.toString());
}
}
public static int generateNumber()
{
int number = 0;
Random random = new Random();
number = random.nextInt(1, 10);
return number;
}
}

How can I get an int calculation into a if in.equals?

I wanted to write a small quiz with an int calculation, but I can not get it to run.
import java.util.Scanner;
public class Quiz {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
String in;
in= scan.nextLine();
System.out.println("What is 4+4?");
if (in.equals (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
You can use scan.nextInt(); to accept int values,
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
int in= scan.nextInt();
System.out.println("What is 4+4?");
if (in == (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
First of all why would you add two numbers when you can keep one number in a variable as the expected result. The input expects a String so you can either change it to int or say String.valueOf(expected result)
int in= scan.nextInt();
Scanner scan = new Scanner(System.in);
final int a = 8;
System.out.println("What is 4+4?");
String in= scan.nextLine();
if (in.equals(String.valueOf(a))) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
Although others suggest using Scanner#nextInt I wouldn't recommend it. It has some kind of nonintuitive behavior and causes harm when used by programmers who are new to Java when trying to read first number, the operator and the second number.
As the OP is already familiar with Scanner#nextLine I would suggest the following approach:
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = sc.nextLine();
int first = Integer.parseInt(a);
int second = Integer.parseInt(b);
int result = first+second;
To design such quiz, I would suggest going a bit further:
public static void main(String[] args) {
Random random = new Random();
Scanner sc = new Scanner(System.in);
int a = random.nextInt(100);
int b = random.nextInt(100);
System.out.println(String.format("What is the result of %d + %d", a, b));
String answer = sc.nextLine();
try {
int result = Integer.parseInt(answer);
if (result == a+b) {
System.out.println("Correct");
} else {
System.out.println("Wrong");
}
} catch (NumberFormatException e) {
System.out.println(answer + " - is not a valid number");
}
}
You need to convert the String value of the the scanner to an int, you can use scan.nextInt() as well but this can lead to problems later with the scanner not progressing to the next line after the int. You also need to order it correctly otherwise it'll ask for input before the question is asked. See below, hope it helps.
import java.util.Scanner;
public class Quiz {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
int in;
System.out.println("What is 4+4?");
in = Integer.valueOf(scan.nextLine());
if (in == (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
String in = scan.nextLine();
if (in.equals(String.valueOf(a+b))) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
Or use Integer.toString(a+b) or "" + (a + b)
Or change Integer in = scan.nextInt()

How do I create a user-defined method that returns the length of a string?

I am trying to write a program that takes a user's input and outputs the number of characters they typed in. I have to do this by creating a method that calculates the amount of characters, then call that method in main to output the results. I was encouraged to use a for loop, but I don't see how that would work. I can calculate the number of characters using length(), but I can't figure out how to make my method work. This is what I have so far:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
return;
}
public static int GetNumOfCharacters(int userCount) {
int i = 0;
String userInput = "";
userCount = userInput.length();
return userCount;
}
}
My method is not returning the length of the string, it just gives me 0 or an error.
Right now, you are never calling your "GetNumOfCharacters" method in your main. The way Java programs work, is by calling the main method and executing line per line what lies there. So you need to call you method from inside the main method. On the other hand, it should get the Stirng as a parameter, so you can get its length. It would look something like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
int lenInput = GetNumOfCharacters(userInput);
System.out.println("The length was: "+lenInput+" characters");
}
public static int GetNumOfCharacters(String userInput) {
int len = userInput.length();
return len;
}
A problem is that you are not actually calling the method
so try
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
System.out.println ("The length is " + GetNumOfCharacters (userInput))
}
// need to pass string into this method
public static int GetNumOfCharacters(String myString) {
int userCount = myString.length();
return userCount;
}
}
Your question included the line:
I was encouraged to use a for loop, but I don't see how that would
work.
There's no elegant way to do this in Java because you are assumed to use String.length() to get the length of strings. There is no 'end of string' marker as there is in, say, C. However you could mimic the same effect by catching the exception thrown when you access past the end of the string:
for (int len = 0; ; len++) {
try {
text.charAt(len);
} catch (StringIndexOutOfBoundsException ex) {
return len;
}
}
That's not a nice, efficient or useful piece of code but it does demonstrate how to get the length of a string using a for loop.
Problems with your code:
No Function call
Add function call in main() as int count=GetNumOfCharacters(userInput);
Parameter datatype mismatch
change the datatype in function definition from int to String as public static int GetNumOfCharacters(String userInput) {
Unwanted return statement in main()
remove the return from main()
Not displaying the value returned from GetNumOfCharacters
Add System.out.print("Number of characters: "+ count); inside main()
Code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
int count=GetNumOfCharacters(userInput);
System.out.print("Number of characters: "+ count);
}
public static int GetNumOfCharacters(String userInput) {
int userCount = userInput.length();
return userCount;
}
OR
Function is not really needed,you can remove the function and do it like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
System.out.print("Number of characters: "+ userInput.length());
}
If you don't want to use predefined methods, you can do like this..
public static void main(String args[]){
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.println("You entered: "+userInput);
char a[]=userInput.toCharArray();
int count=0;
for(char c : a){
count++;
}
System.out.println("length of the string is:"+count);
}

Java program involving substring() and charAt() methods

My program is supposed to print out the initials of the name and print the last name.
Eg. if the name entered is Mohan Das Karamchand Gandhi, the output must be MDK Gandhi. Although I get a "String index out of range" exception.
import java.util.Scanner;
public class name {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
for(int i=0;i<l;i++){
ch=w.charAt(i);
if(ch==32||ch==' '){
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println(w.substring(spacel,l+1));
}
This is the culprit:
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
When i is equal to l - 1, then space1 is going to be equal to l or w.length(), which is beyond the end of the string.
This can be easily achieved using String's split() method or using StringTokenizer.
First split string using space as delimiter. Then according to your format last string would be Last Name and iterate over other string objects to get initial characters.
String name = "Mohan Das Karamchand Gandhi";
String broken[] = name.split(" ");
int len = broken.length;
char initials[] = new char[len-1];
for(int i=0;i<len-1;i++) {
initials[i] = broken[i].charAt(0);
}
String finalAns = new String(initials)+" "+broken[len-1];
import java.util.Scanner;
public class name
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
System.out.print(w.charAt(0) + " ");
for(int i=0;i<l;i++)
{
ch=w.charAt(i);
if(ch==32||ch==' ')
{
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println("\b\b"+w.substring(spacel,l));
}
}

Getting the number of occurrences of one string in another string

I need to input a two strings, with the first one being any word and the second string being a part of the previous string and i need to output the number of times string number two occurs. So for instance:String 1 = CATSATONTHEMAT String 2 = AT. Output would be 3 because AT occurs three times in CATSATONTHEMAT. Here is my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.indexOf(word9);
System.out.println(occurences);
}
It outputs 1 when I use this code.
Interesting solution:
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
Basically what we're doing here is subtracting the length of main from the length of the string resulting from deleting all instances of sub in main - we then divide this number by the length of sub to determine how many occurrences of sub were removed, giving us our answer.
So in the end you would have something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurrences = countOccurrences(word8, word9);
System.out.println(occurrences);
sc.close();
}
You could also try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.nextLine();
String word9 = sc.nextLine();
int index = word8.indexOf(word9);
sc.close();
int occurrences = 0;
while (index != -1) {
occurrences++;
word8 = word8.substring(index + 1);
index = word8.indexOf(word9);
}
System.out.println("No of " + word9 + " in the input is : " + occurrences);
}
Why no one posts the most obvious and fast solution?
int occurrences(String str, String substr) {
int occurrences = 0;
int index = str.indexOf(substr);
while (index != -1) {
occurrences++;
index = str.indexOf(substr, index + 1);
}
return occurrences;
}
Another option:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.split(word9).length;
if (word8.startsWith(word9)) occurences++;
if (word8.endsWith(word9)) occurences++;
System.out.println(occurences);
sc.close();
}
The startsWith and endsWith are required because split() omits trailing empty strings.

Categories