Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having trouble with "//Clinton's delegates in order from highest to lowest". I realize that it's currently in ascending order (I was more familiar with this), but it still isn't looping enough times to even do the ascending order properly. I would like for the third column to be in descending order --> Integer.parseInt(primary[row][2]).
import java.io.*;
public static void main(String[] args) throws IOException
{
//Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);
//2D array
String[][] primary = new String[44][5];
//Section break
System.out.println("1. The file contents are:\n");
//Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
//Set delimiter as "/"
String line;
int i=0;
while((line=br.readLine())!=null){
primary[i]=line.split("/");
i++;
}
//Print text file
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println("");
}
//Clinton's delegates in order from highest to lowest
int temp=0;
for(int row=0; row<primary.length-1; row++){
//Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[row+1][2]);
if(delC > delC1){
temp=delC1;
delC1=delC;
delC=temp;
}
System.out.println(temp);
}
}
Try this:
public static void main(String[] args) throws IOException {
//Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);
//2D array
String[][] primary = new String[44][5];
//Section break
System.out.println("1. The file contents are:\n");
//Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
//Set delimiter as "/"
String line;
int i=0;
while((line=br.readLine())!=null){
primary[i]=line.split("/");
i++;
}
//Print text file
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println();
}
//Clinton's delegates in order from highest to lowest
for(int row=0; row<primary.length-1; row++){
for(int row1=row+1; row1<primary.length; row1++) {
//Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[row1][2]);
if(delC < delC1){
String[]tmpprimary = primary[row];
primary[row] = primary[row1];
primary[row1] = tmpprimary;
}
}
}
System.out.println("\n**************************** Order Descending *******************************");
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println();
}
}
I think your code looks like trying to do bubble sort. If that is what you are trying to do then you need to have 2 for loops to iterate the contents and swap them. Since you are using String array hence the array elements needs to be swapped. not just numbers in the array for display. See the following modified code.
I see you have tagged with selection sort. Let me know if you need that. Bubble sort below because your looked like doing that.
public static void main(String[] args) throws IOException {
// Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);
// 2D array
String[][] primary = new String[44][5];
// Section break
System.out.println("1. The file contents are:\n");
// Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
// Set delimiter as "/"
String line;
int i = 0;
while ((line = br.readLine()) != null) {
primary[i] = line.split("/");
i++;
}
// Print text file
for (int row = 0; row < primary.length; row++) {
for (int col = 0; col < primary[row].length; col++) {
// Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
// Newline
System.out.println("");
}
// Clinton's delegates in order from highest to lowest
int temp = 0;
// bubble sort
for (int row = 0; row < primary.length - 1; row++) {
for (int k = row + 1; k < primary.length; k++) {
// Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[k][2]);
int delO = Integer.parseInt(primary[row][4]);
if (delC >= delC1) {
// swap contents
swap(primary, row, k);
temp = delC1;
delC1 = delC;
delC = temp;
}
}
// System.out.println(temp);
}
// Print output
for (int row = 0; row < primary.length; row++) {
System.out.println(primary[row][2]);
}
}
private static void swap(String[][] primary, int row, int k) {
String[] temp = primary[k];
primary[k] = primary[row];
primary[row] = temp;
}
Related
This code takes two txt files, reads them puts them in 2d arrays and should check if the numbers in the files are magic squares but it keeps returning NumberFormatException error. I'm new to java so if anyone could help me that would be great. I'm pretty sure the problem come from the txt file being string and the 2d array needing to be in int form. But how and where do I make that conversion on my code?
this is what i have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ms {
public static void main(String[] args) throws FileNotFoundException {
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
int nos[][] = null;
nos = getArray(filename1);
boolean b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
System.out.println("\n");
nos = getArray(filename2);
b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
}
private static int[][] getArray(String filename) throws FileNotFoundException {
String line;
int nos[][] = null;
int size = 0, rows = 0;
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
if (!sc.nextLine().isEmpty())
size++;
}
sc.close();
nos = new int[size][size];
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
line = sc.nextLine();
if (!line.isEmpty()) {
String arr[] = line.split("\t");
for (int i = 0; i < arr.length; i++) {
nos[rows][i] = Integer.valueOf(arr[i]);
}
rows++;
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
return nos;
}
private static void printArray(int[][] nos){
for(int i = 0; i<nos[0].length;i++) {
for (int j = 0; j < nos[0].length; j++){
System.out.printf("%-3d",nos[i][j]);
}
System.out.println();
}
}
private static boolean isMagicSquare(int[][] square) {
boolean bool = true;
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++){
for (int col = 0; col < order; col++) {
sumRow[row] += square[row][col];
}
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row++) {
sumCol[col] += square[row][col];
}
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
for (int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
return bool;
}
}
SUGGESTION:
Substitute nos[rows][i] = Integer.valueOf(arr[i]); for a custom method that will tell you WHERE the error is occurring.
EXAMPLE:
public static Integer tryParse(String text, int row, int i) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("ERROR: row=" + row + ", i=" + i + ", text=" + text);
return null;
}
}
CAVEAT: This is for helping you troubleshoot ONLY. You definitely wouldn't want to release this in "production code" ;)
What is the NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Offtopic:
A thing that i can notice is that both filesnames have the same name. So you will verify the same file 2 times.
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
I checked your program and you error appears when you put like this on a file:
1. 5 5
2. 5 5
So the error shows beacause you are trying to parse to int the String "5 5". So your code pick the all line and tries to convert to int and " " it's not an int. And there lives the NumberFormatException error.
How do to solve it?
The function that we will work on is the one that you pass from file to an array in
private static int[][] getArray(String filename) throws FileNotFoundException{
The of the function is after we read the file.
As you said, you are leading with a 2d array so to insert all the numbers we need to have loops for each dimension on the array.
So we will start from there.
I will use a while beacause we are dealing with a string and it's easier to verify the text that its left on the line. Will add a new int variable that starts in 0 to pass in every column of a line to use with the while loop. And with this we got this:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
whileIterator++;
}
whileIterator = 0;
}
Next setep, we will divide in 2 behaviors because we will substring the String that has in the line, and will work differently when it's the last number that we are verifying:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need in a line
}else{//All other iterations
whileIterator++;
}
whileIterator = 0;}
To finalize let's add the new logic to insert in nos array. So lets pick all line for example 2 7 6 and we want to add the number 2, so lets do that. You just need to substring(int startIndex, int finalIndex) the line and add to the nos array. After that let remove the number and the space ("2 ") from the line that we are veryfying.
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need
nos[rows][whileIterator] = Integer.parseInt(line.substring(0));//Add to array
line = "";//To not pass the while verification
}else{//All other iterations
nos[rows][whileIterator] = Integer.parseInt(line.substring(0, line.indexOf(" ")));//Add to array
line = line.substring(line.indexOf(" ") + 1);//remove the number we added behind
}
whileIterator++;
}
whileIterator = 0;}
And here you go, that how you add the numbers to an array and don't get the error.
If you need some further explanation just ask. Hope it helps :)
I'm a beginner in java and I am trying to fill a 2d character array from an input file. To do this I constructed a method which takes in a 2d character array as a parameter variable, then reads the file and stores it as a character array. So far I have done everything except fill the array, as when I run the code the program throws a NoSuchElement exception. If anyone could help me with this I would greatly appreciate it.
public static char [][] MakeWordArray (char [][] givenArray)
{
try
{
File wordFile= new File ("words.txt");
Scanner in= new Scanner (wordFile);
int rows =0;
int col=0;
while (in.hasNextLine())
{
rows = rows + 1;
col = col + 1;
in.next();
}
char [][] words = new char [rows][col];
File wordFile2= new File ("words.txt");
Scanner in2= new Scanner(wordFile2);
for ( int i = 0; i < rows; i++)
{
for (int j = 0; j < col; j++)
{
String wordly = in2.nextLine();
words [i][j] = wordly.charAt(i);
}
}
return words;
}
catch (FileNotFoundException e)
{
System.out.println("File Does Not Exist");
}
return null;
}
I think your counting methods have some problems.
If you want to count how many lines your .txt have:
int counter = 0;
while (in.hasNextLine())
{
counter++;
in.nextLine();
}
If you want to count how many char your .txt have:
int counterWithoutSpace = 0, counterWithSpace = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
while (inLine.hasNext())
{
String nextWord = inLine.next();
counterWithoutSpace += nextWord.length();
counterWithSpace += nextWord.length() + 1;
}
counterWithSpace--;
}
If you want to count how many char you have on each line, I recommend ArrayList. Because the size of your array is dynamic.
Note that you can also you can use the char counter logic above with List too.See as follows:
List<Integer> arr = new ArrayList<Integer>();
while (in.hasNextLine())
{
arr.add(in.nextLine().length());
}
And if you realy needs the static array, you can use:
Integer[] intArr = arr.toArray(new Integer[0]);
You can transform its entire function as below to get a list of every Character of the .txt:
List<Character> arr = new ArrayList<Character>();
while (in.hasNextLine())
{
String line = in.nextLine();
for (char c : line.toCharArray())
{
arr.add(c);
}
}
Try using a do while loop instead of the while
do
{
rows=rows+1;
col=lol+1;
in.next();
}
while(in.hasNext());
There are multiple questions here.
1) Why did you provide a char[][] parameter when you are not even using it?
2) Why are you using two files when all you need to do is read from a file and convert it in 2d Array?
3) The method name should follow camel casing convention.
From what i understood from your question, This is a code i've tried.
NOTE- because the requirement is of an Array and not dynamic datatypes like List ArrayList etc., the data entered into char array might be lost
Saying that here is what works.
public class StackOverflow{
public static char [][] makeWordArray ()
{
try{
File f = new File("C:\\docs\\mytextfile.txt");
Scanner scan = new Scanner(f);
int row = 0, col = 0;
String readData = "";
while(scan.hasNextLine()){
readData += scan.nextLine();
row++;
}
double range = (readData.length()/row);
col = (int)Math.ceil(range);
char[][] arr = new char[row][col];
int count = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
arr[i][j] = readData.charAt(count++);
System.out.println("Pos: ["+ i +"][" + j + "]" + arr[i][j]);
}
}
return arr;
}
catch(FileNotFoundException fe){
System.err.println(fe.getMessage());
return null;
}
}
public static void main(String[] arg){
char[][] myarr = StackOverflow.makeWordArray();
//print your array
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
As per my code, I ask user to enter a string. I want to convert it in 2 dimensional array of NXN size. Although N can be variable but for now considering it to be 3. I want to format the string inputted by the user as below.
For input string :
⌐Φ┼╨¡¬╨┴╨
I want to arrange like this way.
[⌐ Φ ┼
╨ ¡ ¬
╨ ┴ ╨]
Below is the code.
public static void main(String[] args) {
Map<Character,Character> inputMap = new HashMap<Character,Character>();
inputMap.put('a', '|');
inputMap.put('b', 'β');
inputMap.put('c', '⌐');
inputMap.put('d', '≡');
inputMap.put('e', '╨');
inputMap.put('f', 'Ω');
inputMap.put('g', '╟');
inputMap.put('h', '¬');
inputMap.put('i', '↔');
inputMap.put('j', 'Σ');
inputMap.put('k', '¥');
inputMap.put('l', '╒');
inputMap.put('m', '┼');
inputMap.put('n', '«');
inputMap.put('o', 'Φ');
inputMap.put('p', '╔');
inputMap.put('q', 'Є');
inputMap.put('r', '┴');
inputMap.put('s', 'δ');
inputMap.put('t', '╬');
inputMap.put('u', '┤');
inputMap.put('v', 'θ');
inputMap.put('w', '●');
inputMap.put('x', '◙');
inputMap.put('y', 'σ');
inputMap.put('z', '∞');
inputMap.put(' ', '¡');
Scanner ins = new Scanner(System.in);
System.out.println("Enter a String");
String myData = ins.nextLine();
char arr[]=new char[myData.length()];
arr=myData.toCharArray();
for(int i = 0; i < arr.length; i++) {
arr[i]=inputMap.get(arr[i]);
System.out.println( arr[i]);
}
}
how can I do this?
There is a method in String.java toCharArray(). This will give you single dimensional array. Now iterate it using simple for loop. In each iteration you can print the character and at each Nth iteration print a new line.
public static void main(String[] args) {
Scanner ins = new Scanner(System.in);
System.out.println("Enter a String");
String myData = ins.nextLine();
ins.close();
char [] oneDArray = myData.toCharArray();
int N = 3; // or you can set it by asking the user
char[][] twoDArray = new char[N][N];
int size = oneDArray.length;
boolean isEndReached = false;
for(int row = 0; row < N ; row++ ){
for(int col = 0; col < N; col++){
int index = row*N + col;
if(index >= size){
isEndReached = true;
break;
}
twoDArray[row][col] = oneDArray[index];
}
if(isEndReached){
break;
}
}
//printing...
System.out.print("[");
for(int row = 0; row < N ; row++ ){
for(int col = 0; col < N; col++){
System.out.print(twoDArray[row][col]+" ");
}
System.out.println();
}
System.out.print("]");
}
Hope this helps...
You can print blank line at certain interval, e.g.:
String[] array = new String[10];//your map
int n = 5;
int count = 0;
for(String element : array){
count++;
System.out.print(element + " ");
if(count%n == 0){
System.out.println();
}
}
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.
I am fairly new to programming so layman's talk is appreciated.
I have been tasked to read the contents of a file, which will contain 9 values (3x3 array) and then place the contents in the corresponding index.
For instance,
The contents of the 2D array is...
1.00 -2.00 3.00
4.00 1.00 -1.00
1.00 2.00 1.00
After the contents have been read in, they need to be printed. The program will then prompt the user for a scalar multiplier, such as '4.' The program should then print the new array with the new output.
I currently have this,
import java.io.*;
import java.util.*;
public class CS240Lab8a {
/**
* #param args the command line arguments
*/
static double [][] matrix = new double[3][3];
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
// Variables
String fileName = "ArrayValues.txt";
// print description
printDescription();
// read the file
readFile(fileName);
// print the matrix
printArray(fileName, matrix);
// multiply the matrix
multiplyArray(fileName, matrix);
}
// Program Description
public static void printDescription()
{
System.out.println("Your program is to read data from a file named ArrayValues.txt and store the values in a 2D 3 X 3 array. "
+ "\nNext your program is to ask the user for a scalar multiplier \n"
+ "which is then used to multiply each element of the 2D 3 X 3 array.\n\n");
}
// Read File
public static void readFile(String fileName) throws IOException
{
String line = "";
FileInputStream inputStream = new FileInputStream(fileName);
Scanner scanner = new Scanner(inputStream);
DataInputStream in = new DataInputStream(inputStream);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
int lineCount = 0;
String[] numbers;
while ((line = bf.readLine()) != null)
{
numbers = line.split(" ");
for (int i = 0; i < 3; i++)
{
matrix[lineCount][i] = Double.parseDouble(numbers[i]);
}
lineCount++;
}
bf.close();
}
// Print Array
public static void printArray(String fileName, double [][] array)
{
System.out.println("The matrix is:");
for (int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
public static double multiplyArray(String fileName, double[][] matrix)
{
double multiply = 0;
System.out.println("Please enter the scalar multiplier to be used.");
multiply = input.nextDouble();
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
matrix[i][j]
return multiply;
}
} // end of class
I currently have it printing the array properly.
What is the best way to multiply every index value by a constant (user input)?
You're missing an extra step here.
Once you read the line, you have to then split the line and parseDouble on individual numbers.
int lineCount = 0;
while ((line = bf.readLine()) != null)
{
String[] numbers = line.split(" ");
for ( int i = 0 ; i < 3 ; i++)
matrix[lineCount][i] = Double.parseDouble(numbers[i]);
lineCount++;
}
Also, your readFile doesn't need to return anything. Just make your matrix variable global.
ok, the way I look to it:
you read the content of the input file to a string. You already have the method for reading line by line just put everything in a string.
String content = readFile(input.txt);
// Parse lines
String[] lines = content.split("\n");
// Parses values
for(int i = 0; i < lines.length; i++) {
// Get line values
String[] values = lines[i].split(" ");
for(int j = 0; j < values.length; j++) {
// Punt in Matrix
matrix[i][j] = Double.parseDouble(values[j]);
}
}