Unable to convert to Int from String - java

I am working on a solution to the TSP problem. I have generated all the permutations of the String "123456", however, I need to convert this into an ArrayList of Integer like this [1,2,3,4,5,6]...[6,5,4,3,2,1]. I then store this into an ArrayList of ArrayLists. Once there I will be able to compare all of the cities that need to be traveled to.
When I run my code, I have a method to generate the permutation, then a method to change that permutation into an ArrayList of Integer. When I convert them, I get the exception java.lang.NumberFormatException: For input string: "". I don't know of any other way to get the String to Integer
Here is my code.
public static String permute(String begin, String string){
if(string.length() == 0){
stringToIntArray(begin+string);
return begin + string + " ";
}
else{
String result = "";
for(int i = 0; i < string.length(); ++i){
String newString = string.substring(0, i) + string.substring(i+1, string.length());;
result += permute(begin + string.charAt(i), newString);
}
stringToIntArray(result);
return result;
}
}
public static void stringToIntArray(String s){
ArrayList<Integer> perm = new ArrayList<Integer>();
String [] change = s.split("");
for(int i = 0; i < 7; ++i){
int integer = Integer.parseInt(change[i]);
System.out.println(integer);
}
}
public static void main(String[] args) {
permute("", "123456");
}

These lines
String [] change = s.split("");
for(int i = 0; i < 7; ++i){
int integer = Integer.parseInt(change[i]);
System.out.println(integer);
}
Given a String like "12345", when you split it on nothing, it will separate every character. Giving you an array with ["","1","2","3","4","5"]. Since the empty String "" is not a Number, you will get the NumberFormatException. You could change your index i to start at 1 so as to ignore that first empty String.

The split method, when splitting on "", produces an empty string as the first element of the array, so you need to start iterating from i = 1.
Also, it would be safer to stop the iteration at change.length to make sure you process all characters when there are more than 6, and don't go out of bounds if there are fewer.
String [] change = s.split("");
for(int i = 1; i < change.length; ++i){ // ignore first element
int integer = Integer.parseInt(change[i]);
System.out.println(integer);
}

Related

integer manipulation by reading its index

I have a integer value like 4590897, what i have to do is i have to shuffle this integer in a way so that i get output 4759980, its like rading first number and last number and creating a new number. integer value can be any.
i tried some code like by converting number in char array and then iterating it and appending it in StringBuilder but not getting desired result.
Code below
public final class class2 {
public static void main(String[] args) {
int a = 15670;
StringBuilder s2 = new StringBuilder();
String s1 = String.valueOf(a);
char[] ch = s1.toCharArray();
//System.out.println(ch.length);
Outerloop:
for(int i = 0; i <=ch.length-1;i++){
//System.out.println(ch[i]);
for(int j = ch.length-1; j >=0; j--){
s2.append(ch[i]);
s2.append(ch[j]);
break;
}
}
System.out.println(s2);
}
}
i have to shuffle this integer in a way so that i get output 4759980
Try this! I am first converting the number to a string. Then I add the first and last digit, the second and the before last digit, etc. Then, I make sure that the string is the same length as the starting one (in case of numbers with odd-number of digits).
public int scramble(int number) {
String numberString = Integer.toString(number);
int numberLength = numberString.length();
String result = "";
for (int i = 0; i < (numberLength + 2) / 2; i++) {
result += numberString.charAt(i);
result += numberString.charAt(numberLength - i - 1);
}
//Making sure that the resulting string is the same length as the original
//Initially, the result for a number with an odd number of digits, such as 12345
//will be 152344. So you need to make sure the last digit is removed.
result = result.substring(0, numberLength);
return Integer.parseInt(result);
}
What about this. First you decompose your number into digits and then you randomly add them back to each other, by picking a random position to add the digit...
public int scramble(int number) {
//Convert the integer to an Array of strings where each string represents a digit
String[] digits = Integer.toString(number).split("");
//Add the individual digits to a list in random order, using a random position
List<String> resultList = new ArrayList<>();
for (String digit: digits) {
int position = (int) (Math.random()*(resultList.size()));
resultList.add(position, digit);
}
//Convert the list with digits in random order to a string
String resultString ="";
for (String digit: resultList) {
resultString += digit;
}
//Convert the resulting string to an integer and return
return Integer.parseInt(resultString);
}
Take two pointers, start and end. Iterate through the string and append the character from start and end to a new string. Increment start and decrement end untill start and end is same.
public static void main(String args[]){
int num = 45908971;
System.out.println(alternate(num));
}
private static int alternate(int num){
String numStr = Integer.toString(num);
int start = 0;
int end = numStr.length()-1;
StringBuffer newNum = new StringBuffer();
while(start<=end) {
newNum.append(numStr.charAt(start++)).append(numStr.charAt(end--));
}
return Integer.parseInt(new String(newNum.toString()));
}

Counting the number of specific occurrences in a java String

I am attempting to solve a problem where I create a method that counts the number of occurrences of capital and lowercase ("A" or "a") in a certain string. I have been working on this problem for a week now, and the main error that I am receiving is that "char cannot be dereferenced". Can anyone point me in the correct direction on this Java problem? Thank you.
class Main{
public static int countA (String s)
{
String s1 = "a";
String s2 = "A";
int count = 0;
for (int i = 0; i < s.length; i++){
String s3 = s.charAt(i);
if (s3.equals(s1) || s3.equals(s2)){
count += 1;
}
else{
System.out.print("");
}
}
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(countA("aaA")); //3
System.out.println(countA("aaBBdf8k3AAadnklA")); //6
}
}
try a simpler solution
String in = "aaBBdf8k3AAadnklA";
String out = in.replace ("A", "").replace ("a", "");
int lenDiff = in.length () - out.length ();
Also as #chris mentions in his answer, the String could be converted to lowercase first and then only do a single check
the main error that I am receiving is that "char cannot be
dereferenced"
change this:
s.length // this syntax is incorrect
to this:
s.length() // this is how you invoke the length method on a string
also, change this:
String s3 = s.charAt(i); // you cannot assign a char type to string type
to this:
String s3 = Character.toString(s.charAt(i)); // convert the char to string
another solution to accomplishing your task in a simpler manner is by using the Stream#filter method. Then convert each String within the Stream to lowercase prior to comparison, if any Strings match "a" we keep it, if not we ignore it and at the end, we simply return the count.
public static int countA(String input)
{
return (int)Arrays.stream(input.split("")).filter(s -> s.toLowerCase().equals("a")).count();
}
For counting the number of time 'a' or 'A' appears in a String:
public int numberOfA(String s) {
s = s.toLowerCase();
int sum = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == 'a')
sum++;
}
return sum;
}
Or just replace everything else and see how long your string is:
int numberOfA = string.replaceAll("[^aA]", "").length();
To find the number of times character a and A appear in string.
int numA = string.replaceAll("[^aA]","").length();

How do I split a string into even parts then populate an array with those new strings?

I am working on a program and I will be asking the user to input a string full of characters with no spaces. I will then be splitting this string up into parts of three characters each, and I would like to populate an array with these new strings of three characters. So basically what I am asking is how would I create a method that takes an input string, splits it up into separate parts of three, then populates an array with it.
while (i <= DNAstrand.length()-3) {
DNAstrand.substring(i,i+=3));
}
This code will split the string up into parts of three, but how do I assign those values to an array in a method?
Any help is appreciated thanks!
Loop through and add all the inputs to an array.
String in = "Some input";
//in.length()/3 is automatically floored
String[] out = new String[in.length()/3];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
This will ignore the end of the String if it's length isn't a multiple of 3. The end can be found with:
String remainder = in.substring(i, in.length());
Finally, if you want the remainder to be part of the array:
String in = "Some input";
//This is the same as ceiling in.length()/3
String[] out = new String[(in.length()-1)/3 + 1];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
out[out.length-1] = in.substring(i, in.length());
Try this:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> arr = new ArrayList<String>();
String temp = "";
int count = 0;
for(int i = 0; i < text.length(); i++)
{
if(count < 3)
{
temp += String.valueOf(text.charAt(i));
count++;
if(count == 3)
{
arr.add(temp);
temp = "";
count = 0;
}
}
}
if(temp.length() < 3)arr.add(temp);//in case the string is not evenly divided by 3
return arr;
}
You can call this method like this:
ArrayList<Strings> arrList = splitText(and the string you want to split);

Separating the int values based on the occurrance of sequence of the values in java?

i have an integer values as:
1299129912
i want to store it as
12
12
12
in the int v1,v2,v3;
i.e.,when ever 9909 occurs we need to separate the values individually. Is it possible in java. If so please anyone help me.
here is the code I'm trying
int l = 1299129912;
Pattern p = Pattern.compile("99");
Matcher m1 = p.matcher(l);
if (m1.matches()) {
System.out.println("\n");
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method matcher(CharSequence) in the type Pattern is not applicable for the arguments (int)
I suppose you already have the value as a String since 1234990912349909 is more that Integer.MAX_VALUE. Then you can split the string into String[] and do whatever you want with the separate values. E.g. call parseInt on each element.
String[] values = myIntString.split("9909");
for (String value: values) {
int v = Integer.parseInt(value);
}
Yes, it is very possible in java. Just convert the integer to a string and replace the 9909 with a space.
Example:
String s="1234990912349909";
s=s.replaceAll("9909","");
int a=Integer.parseInt(s);
System.out.println(a);
//output would be 12341234
If you know you are always going to have 3 integers named v1, v2, and v3 the following would work:
String[] numbers = l.toString().split("99");
int v1 = Integer.parseInt(numbers[0]);
int v2 = Integer.parseInt(numbers[0]);
int v3 = Integer.parseInt(numbers[0]);
However if you don't know in advance then it might be better to do it like this:
String[] numbers = l.toString().split("99");
int[] v = new int[numbers.length];
for (int i = 0; i < numbers.length; i++)
v[i] = Integer.parseInt(numbers[i]);
I found out this is the easiest way to show you how you can resolve your issue:
I included clear comments on every important step. Please check this:
int num = 1239012390;
// Convert int into a string
String str = String.valueOf(num);
// What separates the values
String toBremoved = "90";
String str1 = "";
// Declare a String array to store the final results
String[] finalStrings = new String[2];
// i will be used as an index
int i = 0;
do {
// Finds and separates the first value into another string
finalStrings[i] = str.substring(0, str.indexOf(toBremoved));
// removes the first number from the original string
str = str.replaceFirst(finalStrings[i], "");
// Remove the next separating value
str = str.replaceFirst(str.substring(str.indexOf(toBremoved), str.indexOf(toBremoved) + toBremoved.length()), "");
// increments the index
i++;
} while (str.indexOf(toBremoved) > 0); // keeps going for a new iteration if there is still a separating string on the original string
// Printing the array of strings - just for testing
System.out.println("String Array:");
for (String finalString : finalStrings) {
System.out.println(finalString);
}
// If you want to convert the values into ints you can do a standard for loop like this
// Lets store the results into an int array
int [] intResults = new int [finalStrings.length];
for (int j = 0; j < intResults.length; j++) {
intResults[j] = Integer.valueOf(finalStrings[j]);
}
// empty line to separate results
System.out.println();
// Printing the array of ints
System.out.println("int Array:");
for (int intResult : intResults) {
System.out.println(intResult);
}
Or in a simplified and more accurate way:
(you can use the example above if you need to understand how it can be done the long way)
int num = 1239012390;
String [] numbers = String.valueOf(num).split("90");
int num1 = Integer.parseInt(numbers[0]);
int num2 = Integer.parseInt(numbers[1]);
System.out.println("1st -> " + num1);
System.out.println("2nd -> " + num2);

Incompatible Data Types Error

I am "attempting" to make a method that will take my string array and compare it to an answer key that I have imported from a data file. Every time I compile I get this incompatible data type error and it is saying that:
Found: java.lang.String
Required: java.lang.String[][]
Am I not doing that?
I have had no luck searching for a solution on here and on Google. They seem to be irrelevant to what I am trying to accomplish.
import java.util.*; // Allows for the input of a scanner method.
import java.io.*; // Allows for the inputting and outputting of a data file.
import java.lang.*; // Allows for the use of String Methods.
//////////////////////////////////////////////////////////////////////////////////////
public class TESTY
{
static Scanner testanswers;
static PrintWriter testresults;
public static void main(String[] args) throws IOException
{
testanswers = new Scanner(new FileReader("TestInput.dat"));
testresults = new PrintWriter("TestOutput.dat");
String StudentID;
String answers;
// Reads first two lines first to know how many records there are.
String answerKey = testanswers.nextLine();
int count = Integer.parseInt(testanswers.nextLine());
// Allocate the array for the size needed.
String[][] answerArray = new String[count][];
for (int i = 0; i < count; i++)
{
String line = testanswers.nextLine();
answerArray[i] = line.split(" ", 2);
}
for(int row = 0; row < answerArray.length; row++)
{
for(int col = 0; col < answerArray[row].length; col++)
{
System.out.print(answerArray[row][col] + " ");
}
System.out.println();
}
gradeData(answerArray, answerKey);
testanswers.close();
testresults.close();
}
///////////////////////////////////////////////////////////
//Method: gradeData
//Description: This method will grade testanswers showing
//what was missed, skipped, letter grade, and percentage.
///////////////////////////////////////////////////////////
public static double gradeData(String[][] answerArray, String answerKey)
{
String key;
double Points = 0;
StringBuilder[] wrongAnswers = new StringBuilder[answerArray.length];
for(int rowIndex = 0; rowIndex < answerArray.length; rowIndex++)
{
String studAnswers[][] = answerArray[rowIndex][1].replace(" ", "S");
for(int charIndex = 0; charIndex < studAnswers[rowIndex][1].length; charIndex++)
{
if(studAnswers[rowIndex][1].charAt(charIndex).equals(key.charAt(charIndex)))
{
Points += 2;
}
if(!studAnswers[rowIndex][1].charAt(charIndex).equals('S'))
{
Points --;
}
else
{
wrongAnswers.setcharAt(charIndex, 'X');
}
}
}
return Points;
}
To get a better idea of what I am doing here is my .dat file:
TFFTFFTTTTFFTFTFTFTT
5
ABC54301 TFTFTFTT TFTFTFFTTFT
SJU12874 TTTFFTFFFTFTFFTTFTTF
KSPWFG47 FT FT FTFTFFTTFFTF
PAR38501 FFFFFFFFFFFFFFFFFFFF
MCY19507 TTTT TTTT TTTT TT TT
This statement, for instance,
String studAnswers[][] = answerArray[rowIndex][1].replace(" ", "S");
gives the compilation error
Type mismatch: cannot convert from String to String[][]
because
answerArray[rowIndex][1].replace(" ", "S"); returns a String.
answerArray is a 2D String array.
answerArray[rowIndex][1] gets
a element from the array which is a string
answerArray[rowIndex][1].replace... replaces a character in that
String with another character, ending up as another String (with
the replaced character)
You are trying to assign it to a String array.
Also, you cannot use equals on primitives (int, char...). You need to use == for comparison.
String studAnswers[][] = answerArray[rowIndex][1].replace(" ", "S");
Here, studAnswers is declared as an array of arrays of Strings, and you initialize it with a String. Indeed, answerArray is an array of arrays of Strings, and answerArray[rowIndex][1] is thus a String. And you replace every white space in this String by an S, which returns another String.
That doesn't make sense.

Categories

Resources