Incompatible Data Types Error - java

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.

Related

Replacing String in Java to get all variations

I'm trying to get a printout of all variations of a certain String. For example, we have this input: AB0C0. The 0 in the 3rd and 5th spots should be treated as variables. The variable characters are 1, 2, and 3 to be placed in the spot of 0. This means there would be all possible variations of this input:
AB1C1
AB2C1
AB3C1
AB1C2
AB1C3
AB2C2
AB2C3
AB3C2
AB3C3
This is just an example. A 5-character long string is a place for 1 to 5 variables. The issue I'm facing is, that it should generate all variations no matter how many variables are in the input in no matter in which place they are.
Scanner scanner = new Scanner (System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
String strOutput1 = input.replaceFirst("0","1");
String strOutput1A = input.replace("0","1");
String strOutput2 = input.replaceFirst("0","2");
String strOutput3 = input.replaceFirst("0","3");
String strOutput4 = input.replaceFirst("0","4");
String strOutput5 = input.replaceFirst("0","5");
System.out.println(strOutput1.toUpperCase());
System.out.println(strOutput1A.toUpperCase());
System.out.println(strOutput2.toUpperCase());
System.out.println(strOutput3.toUpperCase());
System.out.println(strOutput4.toUpperCase());
System.out.println(strOutput5.toUpperCase());
What about this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
//find positions of '0' in input
List<Integer> varPositions = findVarPositions(input);
//create permutations
List<String> permutations = new ArrayList<>();
permutations.add(input);//AB0C0
for (int position : varPositions) {
permutations = permutateAtPosition(permutations, position);
}
//print permutations
for (String permutation : permutations) {
System.out.println(permutation.toUpperCase());
}
}
private static List<Integer> findVarPositions(String input) {
List<Integer> varPositions = new ArrayList<>();
int lastVarPosition = -1;
while ((lastVarPosition = input.indexOf('0', lastVarPosition + 1)) != -1) {
varPositions.add(lastVarPosition);
}
return varPositions;
}
private static List<String> permutateAtPosition(List<String> partialyPermutated, int position) {
List<String> result = new ArrayList<>();
char[] replacements = {'1', '2', '3', '4', '5'};
for (String item : partialyPermutated) {
for (int i = 0; i < replacements.length; i++) {
String output = replaceCharAt(item, position, replacements[i]);
result.add(output);
}
}
return result;
}
private static String replaceCharAt(String input, int position, char replacement) {
//converting to char array, because there's no method like
//String.replaceAtPosition(position, char)
char[] charArray = input.toCharArray();
charArray[position] = replacement;
return new String(charArray);
}
}
It's not fixed to a number of variables.
The idea is to extract positions of '0' and subsequently call the method permutateAtPosition, which takes a partially permutated list and permutates it by one more level.
For "a0b0c0" and values 1-2 it would be ['a0b0c0'], then ['a1b0c0','a2b0c0'], then ['a1b1c0','a1b2c0','a2b1c0','a2b2c0'], and finally ['a1b1c1','a1b1c2','a1b2c1','a1b2c2','a2b1c1','a2b1c2','a2b2c1''a2b2c2'].
This solution keeps everything in memory, so in the general case (unlimited input string) it would be wiser to go with depth-first instead.
I've got another solution for you.
First step, getting the amount of variables:
int variableCount = 0;
for (int i = 0; i < 5; i++) {
if (input.charAt(i) == '0') {
variableCount++;
}
}
Then calculating the amount of results we are expecting:
int countMax = (int)Math.pow(4,variableCount);
Lastly, count up in base 4. Pad the number with 0's and replace the original input 0's:
for (int i = 0; i < countMax; i++) {
String paddedNumbers = format("%" + variableCount + "s",Integer.toString(i, 4)).replace(" ", "0");
int replacedCount = 0;
char[] outputChars = input.toCharArray();
for (int j = 0; j < 5; j++) {
if (input.charAt(j) == '0') {
outputChars[j] = paddedNumbers.charAt(replacedCount);
replacedCount++;
}
}
System.out.println(outputChars);
}

How can I parse my 2d array with a cover array to find a character?

Basically, my assignment is to store a message inside a 2-dimensional array and that message comes with a cover message that is a series of dashes and O's that needs to be "placed over" the original message at a specific coordinate (row, column) to reveal a message. I am currently stuck on how to "place" the cover message over the original message to decode the text. My friends have told me to parse the cover over the message and write a series of if-statements that say "if there is an o, take that dimension in the two dimensional array and add it to a message variable".
This is the message:
"We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty and the pursuit of Happiness. That to secure these rights, Governments are instituted among Men, deriving their just powers from the consent of the governed, --That whenever any Form of Government becomes destructive of these ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to affect their Safety and Happiness."
And this is the cover message:
-O------O-----O-------------------------
--O----O--------------------O------O----
------O---O-----------------------------
----------------------O--------------O--
------------------------------O-----O---
-----------------------------------O----
-------O---------------------O----------
Any help is appreciated, thanks.
Edit: So far I have filled a 2d array with the message and a 2d array with the cover message. The cover message is supposed to fit over the original message array starting at [2][5]. Hope this helps.
import java.io.*;
import java.util.*;
public class M {
public static void main(String[] args) throws FileNotFoundException {
File inFile = new File("input.txt");
Scanner scanFile = new Scanner(inFile);
int lines;
lines = scanFile.nextInt();
String message = "";
for (int i = 0; i <= lines; i++)
message += scanFile.nextLine();
message = message.replace(" ", "");
message = message.replace(",", "");
message = message.replace("-", "");
String[][] am = new String[lines][59];
fill2DArray(am, message);
print2DArray(am);
System.out.println(Arrays.deepToString(am).replace("], ", "]\n"));
String r = scanFile.nextLine();
r = r.replace(",", "");
String ro = r.substring(0,1);
String co = r.substring(1);
int crow = Integer.parseInt(ro);
int ccol = Integer.parseInt(co);
int cline = scanFile.nextInt();
System.out.println(cline);
String cover = "";
for (int u = 0; u <= cline; u++)
cover += scanFile.nextLine();
String[][] cm = new String[cline][40];
fill(cm, cover);
print2DArray(cm);
}
public static void fill2DArray(String[][] arr2D,String message)
{
int counterLetters = 0;
for(int i =0;i<arr2D.length;i++) //arr.2D.length gives row length
{
for(int j = 0;j<arr2D[i].length;j++)//arr2D[].length gives column length
{
arr2D[i][j] = message.substring(counterLetters, counterLetters+1);
counterLetters++;
}
System.out.println();
}
}
public static void fill(String[][] arr2D,String cover)
{
int counterLetters = 0;
for(int i =0;i<arr2D.length;i++) //arr.2D.length gives row length
{
for(int j = 0;j<arr2D[i].length;j++)//arr2D[].length gives column length
{
arr2D[i][j] = cover.substring(counterLetters, counterLetters+1);
counterLetters++;
}
System.out.println();
}
}
public static void print2DArray(String[][] arr2D)
{
for(int i =0;i<arr2D.length;i++) //arr.2D.length gives row length
{
for(int j = 0;j<arr2D[i].length;j++)//arr2D[].length gives column length
{
System.out.print(arr2D[i][j]);
}
System.out.println();
}
}
}
What you could do is iterate over the length of the arrays and check if the element at a specific index in the cover array is O. If it is, then add the element from the message array to a string which will contain the full message:
// Assuming that the cover and message arrays are of type chars
String messageStr = "";
// Since the message and cover arrays should be the same length, it doesn't matter which one is used to get the length of the loop
for (int i = 0; i < messageArray.length; i++) {
for (int j = 0; j < messageArray[i].length; j++) {
if (cover[i][j] == 'O') {
messageStr += messageArray[i][j];
}
}
}

null pointer exception string builder

I am trying to use the setCharAt method in a StringBuilder but I am getting a null pointer exception. Is there a way I can add values to the StringBuilder array I have made so I wont get these error.
From research I have found the .append() method but I'm not even sure how it works.
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 = answerKey;
double Points = 0;
StringBuilder[] wrongAnswers = new StringBuilder[5];
String studAnswers;
for(int rowIndex = 0; rowIndex < answerArray.length; rowIndex++) /// Counting rows
{
studAnswers = answerArray[rowIndex][1].replace(" ", "S"); ///Counts rows, Col stay static index 1
for(int charIndex = 0; charIndex < studAnswers.length(); charIndex++)
{
if(studAnswers.charAt(charIndex) == key.charAt(charIndex))
{
Points += 2;
}
else if(studAnswers.charAt(charIndex) == 'S')
{
Points --;
}
else if(studAnswers.charAt(charIndex) != key.charAt(charIndex))
{
for(int i = 0; i < wrongAnswers.length; i++)
{
wrongAnswers[i].setCharAt(charIndex, 'X');
}
Points -= 2;
}
}
System.out.println(Points);
}
return Points;
}
}
The error is occurring on line 91 :
wrongAnswers[i].setCharAt(charIndex, 'X');
You have declared an array of StringBuilders, but you haven't initialized any of the slots, so they're still null.
Initialize them:
StringBuilder[] wrongAnswers = new StringBuilder[5];
for (int i = 0; i < wrongAnswers.length; i++)
{
wrongAnswers[i] = new StringBuilder();
}
Additionally, using setCharAt won't work here, because initially, there is nothing in the StringBuilder. Depending on what you want here, you may need to just call append, or you may initially want a string full of spaces so that you can set a specific character to 'X'.
StringBuilder[] wrongAnswers = new StringBuilder[5];
does not create 5 empty StringBuilders but 5 null StringBuilders.
You need to call something like
wrongAnswers[i] = new StringBuilder()
in order to initialize your 5 array members.
Your problem is that
StringBuilder[] wrongAnswers = new StringBuilder[5];
does not create 5 StringBuilder objects. It only creates an array with 5 null StringBuilder references. You need to create each StringBuilder separately with a line such as
wrongAnswers[i] = new StringBuilder();
inside a loop over i.

Update 2d String array with method that takes in two 2d string arrays

I have to take in a 2d array and multiple each row of it by the other corresponding 2d array.
Here are the files:
Omaha,104,1218,418,216,438,618,274,234,510,538,740,540
Saint Louis,72,1006,392,686,626,670,204,286,236,344,394,930
Des Moines,116,1226,476,330,444,464,366,230,602,260,518,692
Chicago,408,948,80,472,626,290,372,282,488,456,376,580
Kansas City,308,1210,450,234,616,414,500,330,486,214,638,586
Austin,500,812,226,470,388,488,512,254,210,388,738,686
Houston,454,1086,430,616,356,534,218,420,494,382,476,846
New Orleans,304,1278,352,598,288,228,532,418,314,496,616,882
File Two:
Omaha,7.5
Saint Louis,10.5
Des Moines,8.5
Chicago,11.5
Kansas City,12.5
Austin,10.75
Houston,12.5
New Orleans,9.25
Example: When I compare array[0][0] to price[0][0] the strings match therefore I must take the whole ROW of array[0] and multiply each element by that of price[0][1] to update the array.
Now here is my code:
public static String [][] updateString(String[][] array, String[][] prices)
{
String [][] newArray = new String[array.length][];
for(int row = 0; row < array.length; row++)
{
if (array[row][0].equals(prices[row][0]))
{
for(int i = 0; i<array.length; i++)
{
Double d=Double.parseDouble(array[row][i+1]) * Double.parseDouble(prices[row][1]);
newArray[row][i+1] = d.toString();
}
}
}
return newArray;
}
Here are my errors I'm getting:
Exception in thread "main" java.lang.NullPointerException
at assign_1.DansUtilities.updateString(DansUtilities.java:430)
at assign_1.SalesReportGenerator.main(SalesReportGenerator.java:50)
**line 430 is my method. line 50 is where I call it.
new code:
public static String [][] updateString(String[][] array, String[][] prices)
{
for(int row = 0; row < array.length; row++)
{
if (array[row][0].equals(prices[row][0]))
{
for(int i = 0; i<array[row].length; i++)
{
{Double d=Double.parseDouble(array[row][i]) * Double.parseDouble(prices[row][1]);
array[row][i] = d.toString();}
}
}
}
return array;
heres my new errors:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Omaha"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at assign_1.DansUtilities.updateString(DansUtilities.java:429)
at assign_1.SalesReportGenerator.main(SalesReportGenerator.java:50)
NullPointerException can only be thrown if your array is null. Check in the code that is calling the method.
Other notes to improve your code:
you do not need a new array to store values. You can do it in existing array itself.
your inner for loop must be from 1 to the length of current row not the length of the array so it should be something like:
for(int i=1;i<array[row].length;i++)
And use index i instead of i+1 in loop content.
I suggest to create output of your strings, to see whether they are correctly read from files.
private static void outputString2D(String[][] s, String name) {
for ( int i = 0; i < s.length; i++) {
for ( int j = 0; j < s[i].length; j++ ) {
System.out.println(name + " contains at [" + i + "][" + j + "]:\t" + s[i][j]);
}
}
}
Example how I used it:
public static void main(String[] args) {
String[][] str = new String[2][3];
str[0][0] = new String("I am 0,0.");
str[0][1] = new String("I am 0,1.");
str[0][2] = new String("I am 0,2.");
str[1][0] = new String("I am 1,0.");
str[1][1] = new String("I am 1,1.");
str[1][2] = new String("I am 1,2.");
outputString2D(str, "str");
}
Example output:
str contains at [0][0]: I am 0,0.
str contains at [0][1]: I am 0,1.
str contains at [0][2]: I am 0,2.
str contains at [1][0]: I am 1,0.
str contains at [1][1]: I am 1,1.
str contains at [1][2]: I am 1,2.
Provide us the content of your two strings please.

Unable to convert to Int from String

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);
}

Categories

Resources