Splitting a string at a certain character in java - java

In this code, I'm trying to split a string at a definite position, but it doesn't work and i'm not sure what to put, knowing that I'm trying to have it in the format "xy" without spaces, commas, anything.
import java.util.*;
public class xy {
public static void main(String[] args) {
System.out.println("Enter a number with the format 'xy'. x is the row number and y the column number.");
Scanner scanner = new Scanner(System.in);
String[] xy = scanner.nextLine().split(charAt(1)); // not sure what to put here so I tried charAt but it doesn't work
String x = xy [0];
String y = xy [1];
}
}

In this code, I'm trying to split a string at a definite position, but it doesn't work and i'm not sure what to put, knowing that I'm trying to have it in the format "xy" without spaces, commas, anything
You don't have to use split, there is no delimiter in the input received. Since the expected input is of xy. Receive it as a String and use charAt:
String input = scn.nextLine();
char x = input.charAt(0);
char y = input.charAt(1);
Or
String x = input.substring(0, 1);
String y = input.substring(1);

In this case you don't need to split. You basically know that the first string should go from index 0 to n-1, and then you got a second string from n-1 to "length".
Thus: don't split; simply call substring() twice, and give the required numbers.
And as you only deal with two chards in the first place; just go:
char x = str.charAt(0);
char y = str.charAt(1);
Done.

Related

Why does .equals returns false while comapring identical strings?

im trying to compare a String, which is a part of read file(the file:
Example of read file
1.Dog
2.Cat
3.Bird
4), to a given input by a user, using .equals.
It always returns false, even when i copypaste the printed String.
The code:
File TF = new File("Textfile.txt");Scanner read = new Scanner(TF);
String text="";
while(read.hasNextLine()) {
text = text.concat(read.nextLine()+"\n");
}
int x;
int y;
char a;
char b;
Random dice = new Random();
x=dice.nextInt(3)+1;
y=x+1;
a=(char)(x+48);
b=(char)(y+48);
int first = text.indexOf(a);
int second = text.indexOf(b);
String some=text.substring(first,second);
Scanner write = new Scanner(System.in);
String writein=write.nextLine();
System.out.println(writein.equals(some))
text.substring(first,second) returns a string which contains a trailing line break, e.g. "1.Dog\n", while the string entered will not. To fix it, you could trim the line read from the file:
String some=text.substring(first,second).trim();
The variable some ends with \n (or possibly \r\n on Windows). writein on the other has no trailing newline. When comparing strings, every character has to be equal (which is not the case).
You have multiple possible solutions to solve your problem. One of which is to call stripTrailing() on your string (Java >= 11).
System.out.println(writein.equals(some.stripTrailing()))
Or you could manually reduce the length of the string
String some=text.substring(first, second - 1);

Java - How to create a substring until a non-numerical character is reached?

The title speaks for itself. I'm trying to create a calculator that integrates polynomial functions using basic coding, not just whipping out a math operator to do it for me :). I haven't had to go far until I hit a wall, as I'm unable to find a way to: create a substring of the numbers in the original string until a non-numerical character is reached. i.e. if the string is 123x, I want to create a substring of 123, without the 'x'. Here is what I've got so far:
public static void indefinite()
{
int x = 0;
System.out.print("Enter your function to integrate:\n F ");
Scanner input = new Scanner(System.in);
String function = input.nextLine();
String s1 = "";
for (int i = 0; i < function.length(); i++)
{
s1 = s1 + function.substring(x, i+1);
x = i+1;
}
}
It all looks a bit nonsensical, but basically, if the string 'function' is 32x^4, I want the substring to be 32. I'll figure out the rest myself, but this part I cant seem to do.
p.s. i know the for loop's repetition variable is wrong, it shouldn't repeat until the end of the string if I'm looking at functions with more than just 2x^3. I haven't gotten around trying to figure that out yet, so I just made sure it does it for 1 part.
Use replaceAll() to "extract" it:
String number = str.replaceAll("\\D.*", "");
This replaces the first non digit and everything after it with nothing (effectively deleting it), leaving you with just the number.
You can also go directly to a numeric primitive, without having to use a String variable if you prefer (like me) to have less code:
int number = Integer.parseInt(str.replaceAll("\\D.*", ""));
You could split your string at the letter-digit marks, like so:
str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
For instance, "123x54y7z" will return [123, x, 54, y, 7, z]

How to use charAt to find the location of a char in a string

So I didn't want to use the ascii table to do this. I want to make the user input an alphanumeric(eg A3) and then take the alphabet(A) and find it in the string ABC so itll give me a number between 1-9 instead of having the ascii values. This will make it easier for me to put in a 2d array later.
However when I use System.out.println(abc.charAt(row)); itll say its out of bound bexception because its using the ascii value. How can I make it so that it doesn't
public static void main(String[]args){
Scanner k = new Scanner(System.in);
String abc = "ABCDEFGHIJ";
String ab = "abcdefghij";
abc.equals(ab);
System.out.println("Please enter the attack location:");
while (!k.hasNext("[A-J a-j]+[0-9]")) {
System.out.println("Wrong");
k.next();
}
String location = k.next();
char row = location.charAt(0);
int num = (int) location.charAt(1);
System.out.println(abc.charAt(row));
}
}
Remember, the ascii character for A starts at 65, so if the user enters A3, then you're actually using abc.charAt(65), which obviously is not what you want.
Instead, you need to find the index of the character in the array...
int index = abc.indexOf(row);
Have a look at String#indexOf for more details
You may also want to use Character.toUpperCase to convert the char the user entered to uppercase, which will make it easier to search your String
ps- Also something like row - 65 (or row - 'A' if that's to hard to remember) would give you the same result ;)

Java Array index out og bounds Exception when getting input in java

I got Java ArrayIndexOutOfBoundsException when getting String input in Java. Please help me. This is my code: I edited my code to split using : it says "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at solution2.Solution.main(Solution.java:27)
"
import java.util.Scanner;
public class Solution {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String str = scan.next();
String strarr[] = str.split(",");
String temp = strarr[0];
String temparr[] = temp.split(".");
String temp1 = strarr[1];
String temparr1[] = temp.split(".");
int x1 = Integer.parseInt(temparr[0]);
int x2 = Integer.parseInt(temparr[1]);
int y1 = Integer.parseInt(temparr1[0]);
int y2 = Integer.parseInt(temparr1[1]);
System.out.println(distance(x2,x1,y2,y1));
}
public static int distance(int x1,int y1,int x2,int y2){
int xlen=x2-x1;
int ylen=y2-y1;
return (xlen+ylen)*10-(ylen*5);
}
}
You need to escape the dot character in the String.split() regex, otherwise any character will be matched:
String temparr[] = temp.split("\\.");
For temparr1, I think you meant to use temp1:
String temparr1[] = temp1.split("\\.");
If you are expecting double values you could use Scanner.nextDouble() instead.
Did you notice that you are assigning temp.split() to temparr1 instead of temp1.split()?
Also, split takes in a regular expression as an argument, and as it happens, the regexp . matches just about anything. So, you should correct that.
I assume, from lack of anything disproving my guess, that you are parsing an input of format 1.2,3.4, where 1,2,3, and 4 are arbitrary numbers.
Beside that, Scanner.next reads in the next token, meaning that it will read only "1" from "1.2,3.4". You have to use Scanner.nextLine.

How can I extract the numbers from a string only using charAt(), length() and/or toCharArray() in Java

I have to do this for an assignment in my java class. I have been searching for a while now, but only find solutions with regex etc.
For my assignment however I may only use charAt(), length() and/or toCharArray(). I need to get from a string like gu578si300 for example just the numbers so it will become: 578300.
i know numbers are 48 - 57 in ASCII but i can't figure out how to do this in java. You guys any ideas?
i was thinking about a for loop that checks whether the (int) char is between 48-57 en if so puts the value into a seperate array. Howeevr i dont know how to programm that last thing.
I now have this;
public static String filterGetallenreeks(String reeks){
String temp = "";
for (char c : reeks.toCharArray()) {
if ((int) c > 47 && (int) c < 58)
temp += c;
}
return temp;
however it is not working, it just outputs the same as goes in.
is it something in my mainm which looks like this. If i'm right the return temp; will return the temp string into the reeks string in the main right? why is my input still the same a sthe output?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Voer een zin, woord of cijferreeks in:");
String reeks = sc.nextLine();
if (isGetallenreeks(reeks)){
System.out.println("is getallenreeks");
filterGetallenreeks(reeks);
System.out.println(reeks);
}
Since this is homework I will not be providing the complete solution, however, this is how you should go about it:
Do a for loop that iterates for the total amount of characters within the string (.length). Check if the character is a digit using the charAt and isDigit methods.
You could do a loop that checks a character in the string, and if it's a number, append it to another string:
//I haven't tested this, so you know.
String test = "gu578si300 ";
String numbers = "";
for(int i=0; i<test.length(); i++){
if("0123456789".indexOf(test.charAt(i)) // if the character at position i is a number,
numbers = numbers + test.charAt(i); // Add it to the end of "numbers".
}
int final = Integer.parseInt(numbers); // If you need to do something with those numbers,
// Parse it.
Let me know if that works for you.
It seems like a reasonable approach, but I'd make a couple of changes from what you suggested:
If you need to result as a string then use a StringBuilder instead of an array.
Use character literals like '0' and '9' instead of ASCII codes to make your code more readable.
Update
The specific problem with your code is this line:
temp = temp + (int)c;
This converts the character to its ASCII value and then converts that to a decimal string containing the ASCII value. That's not what you want. Use this instead:
temp += c;

Categories