Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am new in Java and I am trying to read a file and read the contents of a file to 2d array, but I got:
Exception in thread "main" java.lang.NumberFormatException: For input string: "2,"
Here is my code
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class File {
public static void main(String[] args) throws Exception {
String s[] = {"hello the you", "23"};
Scanner input = new Scanner(new BufferedReader(new FileReader("hello.txt")));
int x = 10;
int y = 10;
int[][] desktop = new int[x][y];
while (input.hasNextLine()){
for (int i = 0; i <desktop.length ; i++) {
String[] line = input.nextLine().trim().split(" ");
for (int j = 0; j <line.length ; j++) {
desktop[i][j] = Integer.parseInt(line[j]);
}
}
}
for (int i = 0; i <desktop.length ; i++) {
for (int j = 0; j <desktop[i].length ; j++) {
System.out.print(desktop[i][j] + " ");
}
}
}
}
My hello.txt file is
There should be a specific text at the top of each page
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 1, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
Output should store in 2d array.
Change input.nextLine().trim().split(" "); to input.nextLine().trim().split(", ");. That will remove the , that is causing you problems.
Either of the following will work:
String[] line = input.nextLine().split(",");
for (int j = 0; j < line.length; j++) {
desktop[i][j] = Integer.parseInt(line[j].trim());
}
or
String[] line = input.nextLine().trim().split(", ");
for (int j = 0; j < line.length; j++) {
desktop[i][j] = Integer.parseInt(line[j]);
}
[Update]
Your updated hello.txt has There should be a specific text at the top of each page and also a blank line after that. In order to skip these two lines, use the following piece of code before your while loop:
for (int i=0; i<2 && input.hasNextLine(); i++){
input.nextLine();
}
Related
I have a 2D array that needs it's values to be changed based on user input.
private static double nursesArray[][] = {
{2020, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2021, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2022, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2023, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2024, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
The program revolves around it asking the user for the base wage in the year 2020 for the second column (index 1). The program will then ask the user to enter the percent differences in each of the years below, going down each row in that same column. This process needs to be iterated in each of the columns all the way to the end.
The way I have the rest of my code set up is that it uses the array as an argument for the method.
public class nursesUnion {
private static double nursesArray[][] = {
{2020, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2021, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2022, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2023, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{2024, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
public static void dataEntry(double arr[][]) {
Scanner inp = new Scanner(System.in);
}
...
I really have no idea where to begin for this. Java is a new language for me and I haven't fully wrapped my head around it yet.
Assuming user already knows how many values they need to enter, you can start with this basic verion:
public static void dataEntry(double arr[][]) {
Scanner inp = new Scanner(System.in);
int rows = nursesArray.length;
int columns = nursesArray[0].length;
for (int row = 0; row < rows; row++) {
System.out.println("Please, enter values for year " + nursesArray[row][0]);
// starts with 1 to skip the year.
for (int column = 1; column < columns; column++) {
nursesArray[row][column] = inp.nextDouble();
}
}
}
It just iterates trough rows and columns from left to right, from top to bottom.
public static void dataEntry(double arr[][]) {
Scanner inp = new Scanner(System.in);
for(int column = 1; column < arr[0].length; column++){
System.out.println("Enter base wage for col:"+column);
arr[0][column]=inp.nextInt();
System.out.println("Enter % increase per year");
int increase=inp.nextInt();
for(int row=1; row<arr.length; row++){
arr[row][col] += arr[row-1][column]*increase/100;
}
}
}
I am trying to write a sudoku "solver" and netbeans is giving me 3 error messages relating to StringBuilder. I had different files for each class but it wouldn't compile then either. Every site i have visited has suggested the way I am doing it. Please help.
public class Sudoku {
public static void main(String[] args) {
int[][] mainpuzzle =
{{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 81; i++) {
builder.append("09123456789"); // 11
}
for (int j = 0;j < 9; j++ ) {
for ( int k = 0;k < 9;k++ ) {
if ( mainpuzzle [j][k] != 0 ) {
String replace1 = String.valueOf(mainpuzzle[j][k]);
builder.replace((j*11) + (k*11), (j*11) + (k*11),
replace1);
}
}
}
GetSquareCandidates getSqCandid = new GetSquareCandidates();
StringBuilder builderMarkup = new StringBuilder();
builderMarkup = getSqCandid(builder);
}
}
class GetSquareCandidates {
public StringBuilder GetSquareCandidates(StringBuilder boxPassed)
StringBuilder boxRet = new StringBuilder();
boxRet = boxPassed;
return boxRet;
}
}
Looking at your code, there are a couple of things missing like below
GetSquareCandidates class's GetSquareCandidates method does not have an open curly brace.
getSqCandid(StringBuilder builder) method not defined in your GetSquareCandidates class.
Other than these, please share compilation error messages.
There are only a few errors please find below:
Case 1. If public StringBuilder GetSquareCandidates(StringBuilder boxPassed) is a constructor then it can't return.
Case 2. If it is method then kindly do below changes:
Call the method using builderMarkup = getSqCandid.GetSquareCandidates(builder);
Add { after public StringBuilder GetSquareCandidates(StringBuilder boxPassed).
It is recommended using method name like getSquareCandidates().
So I have a method that takes in a size of an array. My method makes half the array 0's.
int [] arrary2 = new int[arraySize];
for(int i = 0; i < arraySize/2; i++){
arr2[i] = 0;
}
//do rest of code?
return array2;
How do I make the half of the last half my array into 1's and so on.
For example an array of size 14, but the array size could be any size?
[0,0,0,0,0,0,0,1,1,1,1,2,2,3]
Rough algorithm:
Calculate half what's left to do (be careful with odd / even)
Fill that with the current value
Repeat
Sample code:
public static int[] createArray(int size)
{
int[] array = new int[size];
int half = (size / 2) + (size % 2);
int index = half;
int value = 0;
for (int i = 0; i < size; i++) {
if (i == index) {
half = (half / 2) + (half % 2);
index += half;
value++;
}
array[i] = value;
}
return array;
}
Sample output:
15 => 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3
14 => 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3
Here's one way:
import java.util.Arrays;
public class Main {
static int[] createArray(int size) {
int[] result = new int[size];
int limit = (size + 1) / 2;
int start = 0, value = 0, idx = 0;
do {
for (int i = start; i < start + limit && idx < size; ++i)
result[idx++] = value;
start += limit;
limit = (limit + 1) / 2;
++value;
} while (idx < size);
return result;
}
public static void main(String[] args) {
int[] result = createArray(70);
System.out.println(Arrays.toString(result));
}
}
A couple of tests:
14 => [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3]
70 => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4]
To do this keep track of where you want the input value to change, the input value and also how many inserts you want to perform until the next change.
int[] arrary2 = new int[arraySize];
int currentEndPoint = (arraySize / 2) + (arraySize % 2);
int endPointIncrement = currentEndPoint;
int currentInputValue = 0;
for (int i = 0; i < arraySize; i++)
{
if (i == currentEndPoint - 1)
{
currentInputValue++;
endPointIncrement = (endPointIncrement / 2) + (endPointIncrement % 2);
currentEndPoint = currentEndPoint + endPointIncrement;
}
arrary2[i] = currentInputValue;
}
return arrary2;
Hope this helps
I have to make a Sudoku board and have the grid but am confused as how to check for any repetitions across a line or column. The code for my grid is.
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
grid[i][j] = new JTextField();
BoardPanel.add(grid[i][j]);
So basically i want to check for repetition across i and then down j
Here is the code with an example to show it.
This program will tell if there are two equal numbers in vertical and horizontal bars.
public static void main(String args[]) {
// store your puzzle in puzzle variable.
int puzzle[][] = {
{0, 9, 0, 0, 0, 0, 0, 0, 8},
{0, 0, 3, 2, 0, 7, 0, 9, 0},
{0, 6, 0, 0, 0, 0, 7, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 6},
{0, 0, 5, 4, 3, 2, 1, 0, 0},
{4, 0, 0, 7, 0, 0, 0, 0, 0},
{0, 0, 7, 0, 0, 0, 0, 3, 0},
{0, 2, 0, 9, 0, 8, 6, 0, 0},
{1, 0, 0, 0, 0, 0, 0, 4, 0}
};
testHorizontal(puzzle);
testVertical(puzzle);
}
public static void testHorizontal(int[][] puzzle) {
for (int[] arr : puzzle) {
test(arr);
}
}
public static void testVertical(int[][] puzzle) {
int[] cols = new int[puzzle.length];
for (int i = 0; i < puzzle.length; i++) {
for (int j = 0; j < puzzle.length; j++) {
cols[j] = puzzle[i][j];
test(cols);
}
}
}
public static boolean test(int arr[]) {
boolean flag = false;
for (int a : arr) {
for (int b : arr) {
if (a == b) {
flag = true;
System.out.println("equal numbers found.");
break;
}
}
}
return flag;
}
I'm trying to do a depth first traversal. I have no idea if I'm even close. Right now it's printing 1 3 4 5. It should be printing 1 2 4 7 3 5 6. Any help or advice is appreciated. Thanks. :)
Class:
public class myGraphs {
Stack<Integer> st;
int vFirst;
int[][] adjMatrix;
int[] isVisited = new int[7];
public myGraphs(int[][] Matrix) {
this.adjMatrix = Matrix;
st = new Stack<Integer>();
int i;
int[] node = {1, 2, 3, 4, 5, 6, 7};
int firstNode = node[0];
for (i = 1; i < node.length - 1; i++) {
depthFirst(firstNode, node[i]);
}
}
public void depthFirst(int vFirst, int n) {
int v, i;
st.push(vFirst);
while (!st.isEmpty()) {
v = st.pop();
if (isVisited[v]==0) {
System.out.print("\n"+v);
isVisited[v]=1;
}
for ( i=1;i<=n;i++) {
if ((adjMatrix[v][i] == 1) && (isVisited[i] == 0)) {
st.push(v);
isVisited[i]=1;
System.out.print(" " + i);
v = i;
}
}
}
}
//
public static void main(String[] args) {
// 1 2 3 4 5 6 7
int[][] adjMatrix = { {0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 0},
{1, 0, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0 ,0},
{0, 0, 1, 1, 1, 0, 0} };
new myGraphs(adjMatrix);
}
}
If you are looking at Depth First Traversal then following is the code changes you should make
1) First declare your node array as int[] node = {0, 1, 2, 3, 4, 5, 6}. This should be done to avoid array index start (which is 0 ) and your node start number (which is 1). SO here now we assume that new names of your node 1 is 0, node 2 is 1......and node 7 is 6.
2) Instead of doing
for (i = 1; i < node.length-1; i++){
depthFirst(firstNode, node[i]);
}
in myGraphs do :
depthFirst(firstNode, 7);
3)In depthFirst instead of for ( i=1;i<=n;i++) use for ( i=0;i<n;i++) While doing System.out.println in function depthFirst add one to the number as 0 represents node 1, 1 represents node 2 and so on.
Below is your fully functional code I modified :
import java.util.Stack;
public class DFS {
Stack<Integer> st;
int vFirst;
int[][] adjMatrix;
int[] isVisited = new int[7];
/**
* #param args
*/
public static void main(String[] args) {
int[][] adjMatrix = { {0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 0},
{1, 0, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0 ,0},
{0, 0, 1, 1, 1, 0, 0} };
new DFS(adjMatrix);
}
public DFS(int[][] Matrix) {
this.adjMatrix = Matrix;
st = new Stack<Integer>();
int i;
int[] node = {0, 1, 2, 3, 4, 5, 6};
int firstNode = node[0];
depthFirst(firstNode, 7);
}
public void depthFirst(int vFirst,int n)
{
int v,i;
st.push(vFirst);
while(!st.isEmpty())
{
v = st.pop();
if(isVisited[v]==0)
{
System.out.print("\n"+(v+1));
isVisited[v]=1;
}
for ( i=0;i<n;i++)
{
if((adjMatrix[v][i] == 1) && (isVisited[i] == 0))
{
st.push(v);
isVisited[i]=1;
System.out.print(" " + (i+1));
v = i;
}
}
}
}}
A working/tested solution in C#, if someone looking for it.
using System;
using System.Collections.Generic;
namespace GraphAdjMatrixDemo
{
public class Program
{
public static void Main(string[] args)
{
// 0 1 2 3 4 5 6
int[,] matrix = { {0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 0},
{1, 0, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0 ,0},
{0, 0, 1, 1, 1, 0, 0} };
bool[] visitMatrix = new bool[matrix.GetLength(0)];
Program ghDemo = new Program();
for (int lpRCnt = 0; lpRCnt < matrix.GetLength(0); lpRCnt++)
{
for (int lpCCnt = 0; lpCCnt < matrix.GetLength(1); lpCCnt++)
{
Console.Write(string.Format(" {0} ", matrix[lpRCnt, lpCCnt]));
}
Console.WriteLine();
}
Console.Write("\nDFS Recursive : ");
ghDemo.DftRecursive(matrix, visitMatrix, 0);
Console.Write("\nDFS Iterative : ");
ghDemo.DftIterative(matrix, 0);
Console.Read();
}
//====================================================================================================================================
public void DftRecursive(int[,] srcMatrix, bool[] visitMatrix, int vertex)
{
visitMatrix[vertex] = true;
Console.Write(vertex + 1 + " ");
for (int neighbour = 0; neighbour < srcMatrix.GetLength(0); neighbour++)
{
if (visitMatrix[neighbour] == false && srcMatrix[vertex, neighbour] == 1)
{
DftRecursive(srcMatrix, visitMatrix, neighbour);
}
}
}
public void DftIterative(int[,] srcMatrix, int srcVertex)
{
bool[] visited = new bool[srcMatrix.GetLength(0)];
Stack<int> vertexStack = new Stack<int>();
vertexStack.Push(srcVertex);
while (vertexStack.Count > 0)
{
int vertex = vertexStack.Pop();
if (visited[vertex] == true)
continue;
Console.Write(vertex + 1 + " ");
visited[vertex] = true;
for (int neighbour = 0; neighbour < srcMatrix.GetLength(0); neighbour++)
//for (int neighbour = srcMatrix.GetLength(0) - 1; neighbour >= 0; neighbour--)// To make same as recursive
{
if (srcMatrix[vertex, neighbour] == 1 && visited[neighbour] == false)
{
vertexStack.Push(neighbour);
}
}
}
}
}
}
To make display order of iterative same as recursion, we need to push neighbors in reverse order to stack. Took this logic from Amit answer here