I want to scan a String and its content. I want to return an error message if there are any character in the string. For example: int a = myFunction("123"); will save "123" in a, but when the user tries to do something like int a = myFunction("12s32"); it should return the error, because there is a character in the string. This is what i got so far:
public class Parseint {
public static int parseInt(String str) {
if (str == null || str.isEmpty()) {
System.out.println("Der String enthaelt keine Zeichen");
return -1;
} else {
int sum = 0;
int position = 1;
for (int i = str.length() - 1; i >= 0; i--) {
int number = str.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
return sum;
}
}
public static void main(String[] args) {
int a = parseInt("");
System.out.println(a);
}
}
Doing a try and catch like in this link suggests would work perfectly
A simple try and catch
Related
I'm trying to get my code to not only search if a char is present in an array, but also if it is present next to one another. So, if the input is hannah, the output should be hanah. It should only remove a char if it is next to the same char.
import java.util.*;
public class test {
static void removeDuplicate(char str[], int length) {
int index = 0;
for (int i = 0; i < length; i++) {
int j;
for (j = 0; j < i; j++) {
if (str[i] == str[j])
{
break;
}
}
if (j == i)
{
str[index++] = str[i];
}
}
System.out.println(String.valueOf(Arrays.copyOf(str, index)));
}
public static void main(String[] args) {
String info = "hannahmontana";
char str[] = info.toCharArray();
int len = str.length;
removeDuplicate(str, len);
}
}
This my solution
static String removeDuplicate(char str[], int length) {
if (length == 0) return "";
List<Character> list = new ArrayList<>();
list.add(str[0]);
for (int i = 1; i < length; i++) {
if (list.get(list.size() - 1) != str[i]) {
list.add(str[i]);
}
}
return list.stream()
.map(Object::toString)
.collect(Collectors.joining());
}
You can do a recursive call here:
import java.util.*;
public class test {
static String removeDuplicate(String input) {
if(input.length()<=1)
return input;
if(input.charAt(0)==input.charAt(1))
return removeDuplicate(input.substring(1));
else
return input.charAt(0) + removeDuplicate(input.substring(1));
}
public static void main(String[] args) {
String info = "hannahmontana";
System.out.println(removeDuplicate(info));
}
}
You can also try RegExp. Maybe not so fast, but I consider it simpler and more readable.
static String removeDuplicate(char[] chars, int ignored) {
return new String(chars).replaceAll("(.)\\1+", "$1")
}
Thanks for all the great answers! It turns out the solution was really simple. I just needed to change str[j] to str[i-1].
public class Test {
public static String MakeSequence(int N)
{
int j;
N=5;
for (N=5;N>=1;--N)
{
for(j=1;j<N+1;++j)
{
return MakeSequence(5);
}
}
if (N<1)
{
String x = "";
System.out.println(x.isEmpty());
}
}
}
I want to return the sequence 555554444333221 when N=5 and return an empty string if the input parameter N is less than 1, but I'm not sure how to modify the code I made
Be simple and do not add additional checks:
public static String makeSequence(int N) {
StringBuilder buf = new StringBuilder();
while (N > 0) {
buf.append(String.valueOf(N).repeat(N));
N--;
}
return buf.toString();
}
public class Test {
public static String makeSequence(int n) {
String value = " ";
for (int i = n; i >= 1; --i) {
for (int j = 1; j < i + 1; ++j) {
value+= i;
}
}
return value;
}
public static void main(String[] args) {
final String s = makeSequence(5);
System.out.println(s);
}
}
In your code, you always try to assign 5 instead of considering the value send to the method. Above solution returns the sequence and if the parameter N(in code I use n) is less than 1 then returns the empty string.
FYI: As a best practice we start both variable and method names in simple letters.
I'm trying to print a statement vertically, and then backward vertically with two classes so I can practice multiple skills. However, frustratingly, I cannot get my program to work and keep getting a "string index out of range error". I'm not sure if I'm miscalling my functions because I am new to Java.
class Main {
public static void main(String[] args) {
MyString.verPrint("treasure");
MyString.backPrint("treasure");
}
}
public class MyString {
public static String verPrint(String x){
int i = x.length();
while(0 < i){
x = x.charAt(i) + "\n";
i++;
}
return(x);
}
public static String backPrint(String x){
int i = x.length() - 1;
while(i >= 0){
i--;
x = x.charAt(i) + "\n";
}
return(x);
}
}
The problem with your solution is you are updating the input string in the first iteration by assigning a character and a new line to it. Hence, it doesn't work for the latter iterations. I've made some changes in your snippet. You may follow it -
public class Main {
public static void main(String[] args) {
System.out.println(MyString.verPrint("treasure"));
System.out.println(MyString.backPrint("treasure"));
}
}
class MyString {
String x;
public static String verPrint(String x){
int i = x.length();
String y = "";
int j = 0;
while(j < i){
y += x.charAt(j) + "\n";
j++;
}
return(y);
}
public static String backPrint(String x){
int i = x.length() - 1;
String y = "";
while(i >= 0){
y += x.charAt(i) + "\n";
i--;
}
return(y);
}
}
String s="HELLO";
char[] y=s.toCharArray();
for (char x : y) {
System.out.println(x);
}
OUTPUT
H
E
L
L
O
String S="Hello";
S=new StringBuffer(S).reverse().toString();
System.out.println(S);
char[] y=S.toCharArray();
for (char x : y) {
System.out.println(x);
}
You know output
your conditions have problem, while checking for the length and index of x string parameter:
public class Main {
public static void main(String[] args) {
System.out.println(verPrint("treasure"));
System.out.println("-----------");
System.out.println(backPrint("treasure"));
}
public static String verPrint(String x) {
int i = 0;
String result = "";
while (i < x.length()) {
result += x.charAt(i++) + "\n";
}
return result;
}
public static String backPrint(String x) {
int i = x.length() - 1;
String result = "";
while (i >= 0) {
result += x.charAt(i--) + "\n";
}
return result;
}
}
For example, the result of toNumber("3.2ac4.8rw2") would be 10 (=3.2+4.8+2).
My Code that I created is below. However it is failing at what I tend to do and I cannot come up with a solution.
public class toNumber {
public static int toNumber(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char next = s.charAt(0);
if (Character.isDigit(next)) {
return Character.digit(next, 10) + toNumber(s.substring(1));
}
else
{
return toNumber(s.substring(1));
}
}
public static int to1Number(String input)
{
if(input ==null || input.length()==0)
return 0;
if(Character.isDigit(input.charAt(input.length()-1)))
return input.charAt(input.length()-1) +
toNumber(input.substring(0, input.length()-1));
else
return toNumber(input.substring(0, input.length()-1));
}
public static void main(String []args)
{
String input;
Scanner kb = new Scanner(System.in);
System.out.println("please enter some input");
input = kb.nextLine();
System.out.println(to1Number(input));
}
}
**I Tested it like this **
please enter some input
my input: t4343
result returned: 62
If you need it recursive:
public int toNumber(String str) {
char ch = str.charAt(0);
int count = Character.isDigit(ch) ? Character.getNumericValue(ch) : 0;
return str.length() > 1 ? count + toNumber(str.substring(1)) : count;
}
Or java 8 using streams without recursion:
public int toNumber(String str) {
return str.chars()
.mapToObj(i->(char)i)
.filter(Character::isDigit)
.mapToInt(Character::getNumericValue)
.sum();
}
Or with a standard loop without recursion:
public int toNumber(String str) {
int count = 0;
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(Character.isDigit(ch)) {
count += Character.getNumericValue(ch);
}
}
return count;
}
If you also want to count floating numbers, a solution using regular expressions would be the simpler one:
private double toNumber(String str) {
ArrayList<String> nums = new ArrayList<>();
Pattern pattern = Pattern.compile("\\d+(\\.\\d*)?"); // If you want to limit the decimal count to 1: "\\d{1}(\\.\\d{1})?"
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
nums.add(matcher.group());
}
return nums.stream().mapToDouble(Double::valueOf).sum();
}
import java.util.Scanner;
public class PD {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter your number: " );
int number = input.nextInt();
for (int count = 2; count < number; count++) {
String blank = "";
String Snumber = count + blank;
if (isPalindromic(count) && isPrime(count) &&
isPalindromic((int)(Snumber.length())) &&
isPrime((int)(Snumber.length()))){
System.out.println( count + "is double palidromic prime");
}
else
continue;
}
}
// method to find palindromic
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
for (int i = 0, q = 1; i <= (convert.length()/2 - 1); i++, q++) {
if (convert.substring(i,q) == convert.substring(convert.length() - q, convert.length() - i)){
return true;
}
}
return false;
}
// method to find prime
public static boolean isPrime(int count ) {
for (int divisor = 2; divisor <= count/2; divisor++) {
if (count % divisor == 0) {
return false;
}
}
return true;
}
}
Currently the thing compiles and ask for input, but it always results in nothing.
Does someone see something wrong with my program that is obvious wrong.
Overall, the program receives input and has to look through values 2 until it hits the value the user wants and print the ones that follow the if statement.
Your isPalindromic method is not functioning properly. It is not returning true for palindromic numbers. Change it to this:
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
int n = convert.length();
for (int i = 0; i < (n / 2 + 1); i++) {
if (convert.charAt(i) != convert.charAt(n - i - 1)) {
return false;
}
}
return true;
}