It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to read a file with doubles. I locate that problem occurs when I am trying to read decimal numbers. While in case of integers, everything work fine. I am receiving NoSuchElementException exception. Any idea about how to solve my problem? My code:
public class readd {
protected Formatter output;
protected Scanner input = new Scanner(System.in);
private Scanner in = new Scanner(System.in);
protected FileWriter out;
protected BufferedWriter out1;
private String ss;
public int r=1,c=1;
public double[][] output_matrix = null;
public double[][] output_matrix2 = null;
public double[] lap_time = null;
public readd() {
}
public void OpenFileRead(String fileName) { //anoigma tou arxeiou gia diavasma
try {
input = new Scanner(new File(fileName));
System.out.println(fileName);
} catch (FileNotFoundException e) { //sfalma kata tin evresi kai to anoigma tou arxeiou
System.err.println("Sfalma kata to anoigma toy arxeioy");
System.exit(0); //eksodos
}
}
public void Load() { //anagnwsi dedomenwn apo arxeio
// double[][] w1 = null;
int count = 0;
int row = 0, col = 0;
// double [][] w1=null;
try {
while (input.hasNext()) { //oso tha iparxei apothikeumeni eggrafi
count++;
if (count == 1) {
row = input.nextInt();
r = row;
// System.out.println(row);
continue;
} else if (count == 2) {
col = input.nextInt();
// System.out.println(col);
c = col;
continue;
} else {
// System.out.println("col="+col);
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
output_matrix[i][j] = input.nextDouble();
//String ss=new Integer(input.nextInt()).toString();
//w1[i][j]=Double.parseDouble(ss.trim());
// String s1 = new Integer(input.nextInt()).toString();
//double v = Double.parseDouble(s1.trim());
//String s2 = new Integer(input.nextInt()).toString();
//int s = Integer.parseInt(s2.trim());
// System.out.print(output_matrix[i][j]+" ");
}
// System.out.println(" ");
}
//System.out.print(col);
//System.out.print(row);
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
}
}
public static void main(String[] args) {
// TODO code application logic here
double[][] wa1;
readd w = new readd();
w.OpenFileRead("W1.txt");
w.Load();
wa1 = w.output_matrix;
}here
I'd also like some more information.
Generally:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/NoSuchElementException.html
It's the end of an enumerator.
There is an idea
Scanner sc = new Scanner("1.0");
sc.nextDouble();
sc.nextDouble();
throws java.util.NoSuchElementException
just as API Scanner.nextDouble says
* #throws NoSuchElementException if the input is exhausted
enter package read;
import java.util.*;
import java.io.File;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileWriter;
import java.io.FileNotFoundException;
/**
*
* #author zenitis
*/
public class readd {
protected Formatter output;
protected Scanner input = new Scanner(System.in);
private Scanner in = new Scanner(System.in);
protected FileWriter out;
protected BufferedWriter out1;
private String ss;
public int r=1,c=1;
public double[][] output_matrix = null;
public double[][] output_matrix2 = null;
public double[] lap_time = null;
public readd() {
}
public void OpenFileRead(String fileName) {
try {
input = new Scanner(new File(fileName));
System.out.println(fileName);
} catch (FileNotFoundException e) {
System.err.println("Sfalma kata to anoigma toy arxeioy");
System.exit(0);
}
}
public void Load() {
int count = 0;
int row = 0, col = 0;
try {
while (input.hasNext()) {
count++;
if (count == 1) {
row = input.nextInt();
r = row;
continue;
} else if (count == 2) {
col = input.nextInt();
c = col;
continue;
} else {
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
output_matrix[i][j] = input.nextDouble();
}
}
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
}
public static void main(String[] args) {
double[][] wa1;
readd w = new readd();
w.OpenFileRead("W1.txt");
w.Load();
wa1 = w.output_matrix;
}
}here
I dont understand i change dot with comma in my txt file and everything works!!
Related
I want to read and print the numbers from the Textfile (WLTP.txt) in the assets folder as an array, but the output of my code is everytime null. I wonder why it is skipping the try part and jumping to the catch part.
public class WLTPc {
public static void main(String[] args) {
int [] data = readFiles("WLTP.txt");
System.out.println(Arrays.toString(data));
}
public static int [] readFiles(String file) {
try {
File f = new File(file);
Scanner s = new Scanner (f);
int ctr = 0;
while (s.hasNextInt()) {
ctr ++;
s.nextInt();
}
int[] arr = new int[ctr];
Scanner s1= new Scanner(f);
for (int i=0; i< arr.length; i++){
arr[i] = s1.nextInt();
}
System.out.println(Arrays.toString(arr));
return arr;
}
catch (Exception e){
return null;
}
}
}
You are passing file name directly and accessing it in File() object.
As you are accessing file from asset you need to use getAssets().open(file))
It will return InputStream. Pass that InputStream to Scanner() and read you file as you want.
import android.content.Context;
import java.io.IOException;
import java.util.Scanner;
public class WLTPc {
private Context context;
public WLTPc(Context context) {
this.context = context;
}
public int[] readAssetFiles(String file) {
try {
Scanner s = new Scanner(context.getAssets().open(file));
int ctr = 0;
while (s.hasNextInt()) {
ctr++;
s.nextInt();
}
s.close();
int[] arr = new int[ctr];
Scanner s1 = new Scanner(context.getAssets().open(file));
for (int i = 0; i < arr.length; i++) {
arr[i] = s1.nextInt();
}
s1.close();
return arr;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I have a text file:
##########
#.......*#
#.########
#........#
########.#
##.......#
##########
How can I get this to be represented as a 2D character array like this:
char[][] maze = {{##########},
{#.......*#},
{#.########},
{#........#},
{########.#},
{##.......#},
{##########}};
I'm also using a JFileChooser to get the text file and saving it as a java.io.File.
Here's what I have that finds the rows/columns and attempts to store the text file as a 2D char array.
import javax.swing.*;
import java.io.*;
import java.util.*;
/**
* Created by marcusstone on 9/10/15.
*/
public class MazeReader {
public static int colNum;
public static int rowNum;
public static int levels;
public static File textFile;
public char[][] maze = new char[rowNum][colNum];
public int getRows() {
return rowNum;
}
public int getCols() {
return colNum;
}
public void loadFile() {
JFileChooser chooseFile = new JFileChooser();
if (chooseFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
textFile = chooseFile.getSelectedFile();
} else {
textFile = null;
}
}
public void getMazeInfo() {
try {
Scanner myScanner = new Scanner(textFile);
String firstLine = myScanner.nextLine();
colNum = firstLine.length();
rowNum = 1;
levels = 1;
while (myScanner.hasNextLine()) {
String aLine = myScanner.nextLine();
if (aLine.charAt(0) != '-') {
rowNum++;
}
if (aLine.charAt(0) == '-') {
levels++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void getMazeCharArray() throws IOException {
try {
BufferedReader reader = new BufferedReader(new FileReader(textFile));
String line = null;
int x = 0, y = 0;
//draw the maze
for(int i = 0; i < rowNum; i ++){
line = reader.readLine();
System.out.println(line);
}
//add elements to the maze array
for(int i = 0; i < rowNum; i++){
for(int j = 0; j < colNum; j++){
maze[i]=line.toCharArray();
}
}
}catch(IOException e) {
e.printStackTrace();
}
}
public static void main (String[] args) throws IOException {
MazeReader myMazeReader = new MazeReader();
myMazeReader.loadFile();
myMazeReader.getMazeInfo();
System.out.println(rowNum);
System.out.println(colNum);
myMazeReader.getMazeCharArray();
} // end main
} // end class
First you put some tried material, but nevertheless here:
First load file and read from that. Reading data, put into two -dimensional array, with x = y = your boundary,
char[x][y] maze;
.
So here I have code I have HashMap made up by the words in file, I am adding words and writing them on file and it works, but when I use my remove function for some reaseon doesnt do anything here is the code :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
public static int value = 1;
private static Scanner input;
public static Scanner in = new Scanner(System.in);
public static Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) throws FileNotFoundException {
readFile();
System.out.println("Enter number of function wanted" + "\n1 to add"
+ "\n2 for searching by prefix" + "\n3 for deleting");
int choice = in.nextInt();
if (choice == 1) {
System.out.println("enter words seprated by comma");
String wd = in.next();
add(wd);
}
if (choice == 2) {
System.out.println("Enter prefix");
String wd = in.next();
prefixSearch(wd);
}
if (choice == 3) {
System.out.println("ENTER word to delete");
String wd = in.next();
remove(wd);
}
}
public static void readFile() throws FileNotFoundException {
input = new Scanner(file);
boolean done = false;
int value = 1;
while (input.hasNext()) {
String word = input.next().toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
map.put(line[j], value);
value++;
done = true;
}
}
if (done == true) {
System.out.println("Succes");
}
}
public static void prefixSearch(String wd) {
System.out.println("Enter prefix");
String prefix = wd.toLowerCase();
for (Map.Entry<String, Integer> key : map.entrySet()) {
if (key.getKey().startsWith(prefix)) {
System.out.println(key.getKey());
}
}
}
public static void add(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
if (!map.containsKey(line[j])) {
map.put(line[j], value);
value++;
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
continue;
}
}
if (done == true) {
System.out.println("Success");
}
}
public static void remove(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
for (Map.Entry<String, Integer> key : map.entrySet()) {
if (key.getKey().equals(line[j])) {
map.remove(key.getKey(), key.getValue());
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
continue;
}
}
}
if (done == true) {
System.out.println("Succes");
}
}
}
Every other method is working just fine, but remove. Is there something wrong with the loops, maybe use more optimal way or?
The reason for failure is that you're trying to change the map while iterating the entries. As with any collection - if you try to modify it while iterating it you'll get ConcurrentModificationException.
Further, there's a redundant inner for-loop (redundant because the whole purpose of a map is that you won't have to iterate it when you're looking for a specific value/s) which means that you'll try to override the file many times when only once is sufficient.
public static void remove(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
map.remove(line[j]);
}
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
if (done == true) {
System.out.println("Success");
}
}
The issues that I can see in your code are the following:
You forgot a quote when defining the file:
public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt")
should be:
public static File file = new File("C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
The remove() function in a map receives only one parameter, which is the key of the entry you want to remove, so:
map.remove(key.getKey(), key.getValue());
should be:
map.remove(key.getKey());
Also, since your getting the entrySet of your map, maybe you should consider renaming the key variable in the rename() function to entry.
I've submitted many solutions written in Java for this problem on ACM-ICPC Live archive. I followed, strictly all the instructions of writing Java solutions. I even installed JDK 6 on my IDE but I always get Runtime error, any idea what is throwing exception here 'cos I think I handled all exceptions.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
class Main {
BufferedReader read;
BufferedWriter write;
Integer D, N;
String U, S;
ArrayList<String> cryptex;
public static void main(String[] args) {
new Main().solve();
}
private void solve() {
read = new BufferedReader(new InputStreamReader(System.in));
write = new BufferedWriter(new OutputStreamWriter(System.out));
process();
try {
read.close();
write.flush();
write.close();
} catch (IOException ex) {
return;
}
}
private void process() {
try {
D = Integer.parseInt(read.readLine().trim());
} catch (IOException ex) {
return;
}
for (int i = 0; i < D; i++) {
try {
String[] params = read.readLine().trim().split("\\s+");
if (params.length != 3) {
return;
}
N = Integer.parseInt(params[0]);
U = params[1];
S = params[2];
cryptex = new ArrayList<String>(N);
for (int j = 0; j < N; j++) {
cryptex.add(read.readLine().trim());
}
try {
write.write(U + " " + solveCase());
} catch (Exception ex) {
return;
}
write.newLine();
read.readLine();
} catch (IOException ex) {
return;
}
}
}
private String solveCase() throws Exception {
Integer n = null, f = null, add = null;
for (int i = 0; i < N; i++) {
if (S.charAt(i) != '_') {
n = cryptex.get(i).indexOf(S.charAt(i));
f = cryptex.get(i).indexOf(U.charAt(i));
add = n - f;
break;
}
}
if (n == null || f == null || add == null) {
throw new Exception("Incorrect test case exception.");
}
char[] ret = S.toCharArray();
for (int i = 0; i < N; i++) {
f = cryptex.get(i).indexOf(U.charAt(i));
n = (add + f + 26) % 26;
ret[i] = cryptex.get(i).charAt(n);
}
return new String(ret);
}
}
Any idea on what I might be doing wrong?
In your process method, you call
D = Integer.parseInt(read.readLine().trim());
This is not optimal. Use a scanner.
Your line should look more like this:
Scanner sc = new Scanner(System.in);
//...
try {
D = sc.nextInt(); // Number of test cases
N = sc.nextInt(); // Rings
U = sc.next(); // Unlocking word
}
//...
Also, note that there will likely be more than one test case, so process() or some other method will need to be inside a for loop.
Hi there I have been having trouble appending entered data to the end of a binary file, having looked up how to do so I found a solution here on stack overflow:
try {
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("BinaryWrite.hagl", true));
out.writeObject(allTowns);
out.flush ();
}
catch (Exception e){
System.out.println("IMPOSSSIBLE");
}
In this piece of code allTowns is my array in which the data I wish to add is held. The problem I am getting is that when I run my program and it displays what is in the file at the end this piece of code never writes to the file at all, I was wondering if anyone could help me understand why this does not work or even just recommend a different method if necessary.
My full code (this part is currently commented out so one can easily create the file):
import java.util.*;
import java.io.*;
public class CoastaslTowns implements Serializable
{
public static Scanner input = new Scanner(System.in);
String name, county;
int population, area;
public static int count = 0;
public static int continuation = 0;
public static CoastaslTowns[] allTowns = new CoastaslTowns[50];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
for (int i=0; i < 50; i++) {
allTowns[i] = new CoastaslTowns();
}
while (loop1 == 0) {
System.out.println("Please enter the name of the town.");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides.");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town.");
int populationEntered = input.nextInt();
System.out.println("Please enter the area of the town.");
int areaEntered = input.nextInt();
input.nextLine();
System.out.println("Are you satisfied with your entries?");
String satisfaction = input.nextLine();
if (satisfaction.equals("yes")) {
loop1 = 5;
System.out.println("Thank you for entering your details");
continuation = 1;
}
else if (satisfaction.equals("no")) {
System.out.println("Would you like to continue and enter more towns?");
String countychecker = input.nextLine();
if (countychecker.equals("yes")) {
}
else {
break;
}
}
writeToFile(nameEntered, countyEntered, populationEntered, areaEntered);
}
ReturnTowns();
}
public static void inputVariations(){
}
public static void writeToFile(String nameEntered, String countyEntered, int populationEntered, int areaEntered) {
int loop2 = 0;
while (loop2 == 0){
allTowns[count].population = populationEntered;
allTowns[count].name = nameEntered;
allTowns[count].county = countyEntered;
allTowns[count].area = areaEntered;
if (continuation == 1) {
loop2 = 1;
}
else {
loop2 = 1;
}
count = count + 1;
}
try {
FileOutputStream fileOut = new FileOutputStream("BinaryWrite.hgal");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allTowns);
out.close();
fileOut.close();
} catch (IOException i) {}
/*
try {
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("BinaryWrite.hagl", true));
out.writeObject(allTowns);
out.flush ();
}
catch (Exception e){
System.out.println("IMPOSSSIBLE");
}
*/
}
public static void ReturnTowns(){
{
int x = 0;
CoastaslTowns[] bw = null;
try {
FileInputStream fileIn =
new FileInputStream("BinaryWrite.hgal");
ObjectInputStream in = new ObjectInputStream(fileIn);
bw = (CoastaslTowns[]) in.readObject();
while (bw[x].population != 0) {
System.out.println(bw[x].name);
System.out.println(bw[x].county);
System.out.println(bw[x].population);
System.out.println(bw[x].area);
System.out.println();
x++;
}
in.close();
fileIn.close();
} catch (IOException i) {
} catch (ClassNotFoundException c) {
}
}
}
}
Any help would be greatly appreciated.