Java - make sure each letter does not contain a number - java

Very new to programming, just starting a Java class.
Here is what the assignment says
1.) Input, via a question in the console, the report owner’s first name as a string and build the last name via input, one character at a time.
a. Check, conditionally, to make sure the first name and last name don’t contain any numeric characters, numbers between 0 – 9. If it does you must remove it. The names can not contain any white space either or special characters.
I already did the first part, and here is my code:
package inclassassignment;
import java.util.Scanner;
public class inclassassignment {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println ("Enter your first name");
String temp;
Scanner your_name = new Scanner (System.in);
temp = your_name.nextLine();
System.out.println(temp);
int n = 0;
System.out.println ("Enter your last name");
String temp1;
temp1 = "";
while (n < 6) {
System.out.println("Please print the next letter of your last name");
String nextletter1;
Scanner lastname = new Scanner (System.in);
nextletter1 = lastname.nextLine();
char nextletter = nextletter1.charAt(0);
temp1 = temp1 + nextletter;
n++;
}
System.out.println(temp1);
{
}
}
}
// I now need to do the part that says to check each ASCII value and make sure none of the letters contain a number. I'm pretty sure this requires an "if else" statement but I've never written one to success.
edit: I should point out I am not allowed to have any static variables or methods in any class except for the class with the main method.

According to your task, you can do it in this way:
int n = 0;
System.out.println("Enter your last name");
String lastName = "";
while (n < 6) {
System.out.print("Please print the next letter of your last name: ");
String tmp = your_name.nextLine();
char c = tmp.charAt(0);
if (Character.isAlphabetic(c)) {
lastName += c;
n++;
} else {
System.out.println("You can use only letters! Try again!");
}
}
System.out.println(lastName);

You can use regular expressions
Scanner sc=new Scanner(System.in);
String s= sc.nextLine(); //read the string
String regex1 = "\\d+" // the regular expression for numbers
if(s.matches(regex1)) // check if the string contains numbers
System.out.println("contains numbers");

I would start with a utility method to normalize names based on your required rules, Character.isUpperCase(char) or Character.isLowerCase(char) and a for-each loop over String.toCharArray() like,
static String normalizeName(String name) {
StringBuilder sb = new StringBuilder();
for (char ch : name.toCharArray()) {
if (Character.isUpperCase(ch) || Character.isLowerCase(ch)) {
sb.append(ch);
}
}
return sb.toString();
}
Then you can call it (and I would use it for both firstName and lastName, for consistency). Like,
public static void main(String[] args) {
System.out.println("Enter your first name");
Scanner scan = new Scanner(System.in);
String firstName = normalizeName(scan.nextLine());
System.out.println("Enter your last name");
String lastName = normalizeName(scan.nextLine());
System.out.printf("Hello %s %s%n", firstName, lastName);
}

Pretty sure this is posted elsewhere
str.matches(".*\\d+.*")// To check if string contains numbers

Try this function:
public String removeNum(String in){
String[] input= in.split("");
String num= "0123456789";
String[] numbers= num.split("");
List<String> numbersToDelete = Arrays.asList(numbers);
for(int i=0;i<input.length;i++){
if(numbersToDelete.contains(input[i])){
input[i]="";
}
}
//Converting from Array back to String
String out = "";
for(int j=0;j<input.length;j++){
out=out+input[j];
}
return out;
}

Related

If condition is met -> scan input into one variable. If not -> scan input into another variable

Scanner input = new Scanner(System.in)
System.out.print("Enter either a string or a number");
String str = input.nextLine();
int x = input.nextInt();
The program here expects 2 values, a string and an integer. YET there is only one.
I want str to register the value if it is a string, BUT if it is an integer, I want the value to be registered by x
In other words, I only want one of the variables to be active
if the value of entered is an integer, then you can simply use regex where
if(str.matches("\\d+") || str.matches("-\\d+"))
checks if the entered number is a number of 1 or more digits or the entered number is a negative number with one or more digits
and if that is the case, then you can x = Integer.parseInt(str); to convert that entered string into integer and make str = ""; otherwise , the entered string is stored in str and never parsed to int
and this is the edited code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter either a string or a number\n");
String str = input.nextLine();
int x = 0;
if(str.matches("\\d+") || str.matches("-\\d+"))
{
x = Integer.parseInt(str);
str = "";
}
else
{
// nothing to do
}
System.out.println("x = " + x);
System.out.println("str = " + str);
}
}
and this is some example output:
Enter either a string or a number
10
x = 10
str =
Enter either a string or a number
test
x = 0
str = test
Enter either a string or a number
-30
x = -30
str =
Enter either a string or a number
test10
x = 0
str = test10
The answer provided by abdo and the comment by Jesse are both valid and very good answers.
However it is also possible to achieve your goal with the Scanner methods. In this case hasNextInt() is your friend.
f
But note, that nextLine() will consume the line break, while nextInt() will not. IMHO it will be more clear to code both options alike and use next() instead.
The most simple approach:
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine(); // consume the line break, too
Here still one issue remains: By default Scanner uses whitespace as delimiter, not line breaks. With the input "4 2\n" nextInt() will return 4 and nextLine() will discard the rest. However the user's intention (number versus string) is not obvious in this case either, therefor I'd tend to create the string "4 2" instead. This can easily be achieved by using line breaks as delimiter instead:
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
A full demo example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
System.out.println("Enter either a string or a number");
String str = null;
while (!"end".equals(str)) {
int x = 0;
str = null;
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine();
if (str != null) {
System.out.printf("we have a string! str=%s%n", str);
}
else {
System.out.printf("we have a number! x=%d%n", x);
}
}
System.out.println("goodbye!");
}
}

with help of only charAt() and isSpaceChar() make first latter uppercase in java

I want to use only charAt() and toUpperCase() function and capitalize the first letter of each word in a sentence.
Like make the letter capital, that is just after the space.
I tried with this following code.
import java.util.Scanner;
class firstscap
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a sentence");
String s=sc.nextLine();
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(Character.isSpaceChar(c))
{
char ch=s.charAt(++i);
ch=ch.toUpperCase();
}
}
System.out.println(s);
}
}
Several problems here.
s.charAt(n) gives you the n-th character of the String, not a pointer to the n-th character of the String. Changing that character does nothing to the String.
Also Strings are not mutable, which means you have no way to change them.
You can start build a new String from parts of the old String plus the Chars you have made uppercase.
You are capitalizing the characters but not storing them anywhere. I recommend you append all the characters to a StringBuilder*.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine().trim(); // Input & omit leading/trailing whitespaces
StringBuilder sb = new StringBuilder();
// Append the first character, capitalized
if (s.length() >= 1) {
sb.append(Character.toUpperCase(s.charAt(0)));
}
// Start with character at index 1
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isSpaceChar(c)) {
sb.append(c).append(Character.toUpperCase(s.charAt(++i)));
} else {
sb.append(c);
}
}
s = sb.toString();
System.out.println(s);
}
}
A sample run:
Enter a sentence: hello world how are you?
Hello World How Are You?
* You can use String instead of StringBuilder but I recommend you use StringBuilder instead of String for such a case because repeated string concatenation in a loop creates additional as many instances of String as the number of concatenation. Check this discussion to learn more about it.
Strings are immutable, you can't modify them.
Consider building a new String for the result e.g by using StringBuilder.
In the following example, a boolean flag is used to know if the last character was a space .
Also we check if the current character is a letter before putting it to upper case, otherwise it makes no sense.
This will also prevent possible crashes if the line ends with a space (since index charAt(i+1) would crash):
public static void main(final String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a sentence");
String s = sc.nextLine();
boolean wasSpace = false;
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (wasSpace && Character.isLetter(c)) {
resultBuilder.append(Character.toUpperCase(c));
} else {
resultBuilder.append(c);
}
wasSpace = Character.isSpaceChar(c);
}
System.out.println(resultBuilder.toString());
}
Note :
If you also want the first letter of the whole sentence to be capitalized, just initialize wasSpace to true .
import java.util.Scanner;
public class A {
public static void main(String args[]) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the string: ");
String a1 = (obj.nextLine()).trim();
String s1 = "";
char c2;
char arr[] = a1.toCharArray();
for (int i = 0; i <= a1.length() - 1; i++) {
if (Character.isSpaceChar(arr[i]) == true) {
++i;
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + " " + c2;
} else {
if (i == 0) {
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + "" + c2;
} else {
s1 = s1 + arr[i];
}
}
}
System.out.println(s1);
}
}

Java string to array and replace a certain word from user to uppercase

Here is the full Question:
...
My Code
import java.util.Scanner;
import java.lang.StringBuilder;
public class javaAPIString {
public static void main(String[]args)
{
String SentenceFromUser = "";
String IndiWordFromUser = "";
/// String upper = IndiWordFromUser.toUpperCase();
//String[] words = SentenceFromUser.split("\\s+");
char ans;
Scanner keyboard = new Scanner(System.in);
do
{
final StringBuilder result = new StringBuilder(SentenceFromUser.length());
String[] words = SentenceFromUser.split("\\s");
System.out.println("Enter a sentence :");
SentenceFromUser = keyboard.nextLine();
System.out.println("Enter a word : ");
IndiWordFromUser = keyboard.next();
/// IndiWordFromUser = upper;
for(int i =0; i > words.length; i++ )
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
// System.out.println("The Output is : " + SentenceFromUser);
System.out.println("Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.");
ans = keyboard.next().charAt(0);
}
while ((ans == 'Y') || (ans == 'Y'));
}
}
My Output/ problem of my code :
Enter a sentence :
i like cookies
Enter a word :
cookies
The Output is : i like cookies
Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.
it returns the same original sentence without changing to Uppercase of the second input to replace to all CAPS.
I hope my solution will help you out! :)
import java.util.Scanner;
public class Solution {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
getTextFromUser();
}
private static void getTextFromUser() {
print("Enter Sentence Here: ");
String text = in.nextLine();
print("\nDo you want to capitalize words in sentence? Y/N: ");
while (in.nextLine().equalsIgnoreCase("y")) {
print("Enter Word: ");
print("Modified Text: " + changeWord(text, in.nextLine()));
print("\n\nDo you want to capitalize words in sentence? Y/N");
}
}
private static String changeWord(String text, String word) {
return text.replaceAll("\\b" + word + "\\b" /* \\b Means word
boundary */, word.toUpperCase()); // No validations done.
}
private static void print(String message) {
System.out.print(message);
}
}
Just some things:
please use java naming conventions for variables name
when you execute your code this instruction will overwrite the user input with an empty string.
IndiWordFromUser = upper;
String[] words = SentenceFromUser.split("\\s");... you are splitting an empty string the first time and the old sentence the other runs
The variable IndiWordFromUser is never read

How do you check if a string is a palindrome in java?

I am trying to write a program that checks if a string is a palindrome and so far I know I am on the right path but when I enter my code it keeps on running for ever. I don't know what the problem is and would like help finding out the solution. In my program I want the user to enter word or words in the method Printpalindrome and then the program should know if the string is a palindrome or not.
Here is my code:
...
Scanner console = new Scanner (System.in);
String str = console.next();
Printpalindrome(console, str);
}
public static void Printpalindrome(Scanner console, String str) {
Scanner in = new Scanner(System.in);
String original, reverse = "";
str = in.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- ) {
reverse = reverse + str.charAt(i);
}
if (str.equals(reverse))
System.out.println("Entered string is a palindrome.");
}
}
Because of this line:
n = in.nextLine();
your program is waiting for a second input, but you already got one before entering the function.
Remove this line and it works.
Here's your program, cleaned (and tested) :
public static void main(String[] args){
Scanner console = new Scanner (System.in);
String n = console.next();
Printpalindrome(n);
}
public static void Printpalindrome(String n){
String reverse = "";
for ( int i = n.length() - 1; i >= 0; i-- ) {
reverse = reverse + n.charAt(i);
System.out.println("re:"+reverse);
}
if (n.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is NOT a palindrome.");
}
Of course, this isn't the best algorithm, but you already know there are many QA on SO with faster solutions (hint: don't build a string, just compare chars).
Remove
Scanner in = new Scanner(System.in);
and
n = in.nextLine();
from Printpalindrome function
and it should work.
This can be implemented in a far more efficient manner:
boolean isPalindrom(String s){
if (s == null /* || s.length == 0 ?*/) {
return false;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
The argument for PrintPalindrom is ignored. You read another value with `in.nextLine()'. Which is the reason for your issues.
Ur code with some correction:-
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
I tried your code and what i observed was that :
first of all you are making a string to enter on the line 2 of your code:
String n=console.next();
next the the program again goes to waiting when this line gets executed:
n = in.nextLine();
actually this particular line is also expecting an input so that is why the program halt at this point of time.
If you enter your String to be checked for palindrome at this point of time you would get the desired result .
But I would rather prefer you to delete the line
n = in.nextLine();
because, with this, you would have to enter two words which are ambiguous.

Java: how to print a dataset of strings as entered except in reverse order?

This program should input a dataset of names followed by the name "END". The program should print out the list of names in the dataset in reverse order from which they were entered. What I have works, but if I entered "Bob Joe Sally Sue" it prints "euS yllaS eoJ boB" insead of "Sue Sally Joe Bob". Help!?
import java.util.Scanner;
public class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner kb = new Scanner(System.in);
System.out.println("Enter a list of names, followed by END:");
original = kb.nextLine();
int length = original.length();
while (!original.equalsIgnoreCase("END") ) {
for ( int i = length - 1; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
original = kb.next();
}
System.out.println("Reverse of entered string is: "+reverse);
}
}
I think that you need to use this simple algorithm. Actually you're not using the proper approach.
Take the whole string which contains all the names separated by spaces;
Split it using as a delimiter the space (use the method split)
After the split operation you will get back an array. Loop through it from the end (index:array.length-1) to the starter element (1) and save those elements in another string
public String reverseLine(String currLine) {
String[] splittedLine = currLine.split(" ");
StringBuilder builder = new StringBuilder("");
for(int i = splittedLine.length-1; i >= 1; i--) {
builder.append(splittedLine[i]).append(" ");
}
return builder.toString();
}
I've supposed that each lines contains all the names separated by spaces and at the end there is a string which is "END"
A quick way, storing the result in the StringBuilder:
StringBuilber reverse = new StringBuilder();
while (!original.equalsIgnoreCase("END")) {
reverse.append(new StringBuilder(original).reverse()).append(" ");
original = kb.next();
}
System.out.println("Reverse: " + reverse.reverse().toString());
Using the approach suggested in the comments above is very simple, and would look something like:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
while (sc.hasNext())
{
String name = sc.next();
if (name.equals("END"))
{
break;
}
names.add(name);
}
Collections.reverse(names);
for (String name: names)
{
System.out.println(name);
}
System.out.println("END");
}
Let the Scanner extract the tokens for you, no need to do it yourself.

Categories