Why Does the following program terminate without an error - java

Why the following program terminate without producing any thing? MyData.txt file is saved in the same directory.
import java.util.Scanner;
import java.io.*;
public class MyIO
{
public static void main (String[] args) throws IOException
{
int num, square;
Scanner scan = new Scanner( "MyData.txt"); // connect a Scanner to the file
try{
while(scan.hasNextInt()) // is there more data to process?
{
num = scan.nextInt();
square = num*num ;
System.out.println("The square of " + num + " is " + square);
}
} finally{
scan.close();
}
}
}

Are you expecting integers from your MyData.txt file only? If the first value of the file isn't an integer, this will not enter the while loop.
It may be possible that you've skipped a line in your code or something. Can we have a look at your MyData.txt file? (or at least an example)
Additionally, you do not need to declare the fields 'num' and 'square' outside of your loop, if you want to do some cleaning up, unless you plan on reusing them later..?

Related

Take the whole line of a java chain and lenth

I am trying to make a java program that given a string, I return the length of it, but I do not know why it does not catch me all. I'm starting with the programing. I've got here.
import java.util.Scanner;
public class lengt {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
String cad = in.next();
System.out.println (cad);
System.out.println ("The length is:" + cad.length ());
}
}
There is a problem in your solution. in.next(); just take the first word of the chain, the one that is most immediate. If instead of using that you put it in.nextLine(); It takes you all the line you enter. You also have to be careful with length, which goes from 0 to n-1, when it comes to taking the length, since you could take one more and unnecessary. The solution for the problem that you pose would be, and there may be more, but one valid
import java.util.Scanner;
public class Example {
public static void main (String [] args) {
Scanner in= new Scanner (System.in);
String cad = in.nextLine();
System.out.println (cad);
System.out.println ("The length is:" + cad.length() - 1); //you can remove -1
}
}

my program reads from the file but cant find the words

So my program knows where the file is and it can read how many words it has, however, I am trying to compare words to count the occurrences of a word that i will use with a scanner.
The program says i can't convert string to a boolean which i understand but how would i be able to make it happen?
can I get an answer why it runs but doesn't allow me to find the word to look for
thanks
import java.util.*;
import java.io.*;
public class wordOccurence {
public static void main(String[] args) throws IOException {
{
int wordCount=0;
int word =0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter file name");
System.out.println("Enter the word you want to scan");
String fileName=scan.next().trim();
Scanner scr = new Scanner(new File(fileName));
// your code goes here ...
while(scr.nextLine()){
String word1 = scr.next();
if (word1.equals(scr)){
word++;
}
}
System.out.println("Total words = " + word);
}
}
}
At present you are only checking if there is a next line available:
while(scr.hasNextLine()){
but you are not fetching it. Its like you are staying at the same position in the file forever.
To fetch the next line, you can make use of
scanner.nextLine()

Java end of file [closed]

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 7 years ago.
Improve this question
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner line = new Scanner(System.in);
int counter = 1;
while (line.hasNextLine()) {
String line = line.nextLine();
System.out.println(counter + " " + line);
counter++;
}
}
}
Task: Each line will contain a non-empty string. Read until EOF.
For each line, print the line number followed by a single space and the line content.
Sample Input:
Hello world
I am a file
Read me until end-of-file.
Sample Output:
1 Hello world
2 I am a file
3 Read me until end-of-file.
If you'd like to scan from a file, you can use the below code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("input.txt"));
int counter = 1;
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(counter + " " + line);
counter++;
}
}
}
Scanner line = new Scanner(); // <-- YOUR ERROR - there is no constructor for the Scanner object that takes 0 arguments.
// You need to specify the environment in which you wish to 'scan'. Is it the IDE? A file? You need to specify that.
Since you said EOF, I'm assuming there is a File associated with this task.
Create a File object, toss that into the Scanner constructor.
File readFile = new File(PATH_TO_FILE); // where PATH_TO_FILE is the String path to the location of the file
// Set Scanner to readFile
Scanner scanner = new Scanner(readFile);
You also have a duplicate local variable named: line
I suggest you do more reading to get a grasp of how variables and objects work rather than guess or be spoonfed code you don't understand. That's how you become a strong programmer.
Documentation states that you need to pass Source to Scanner, so that it can scan from it.
To get user input then you need to use Scanner(InputStream source) constructor.
Scanner line = new Scanner(System.in);
public static void main(String[] args) {
Scanner line = new Scanner(System.in); // Added source parameter in constructor.
int counter = 1; // Initialization of counter is done outside while loop, otherwise it will always get initialized by 1 in while loop
while (line.hasNextLine()) {
String lineStr = line.nextLine(); // changed variable name to lineStr, because 2 variable can't be declared with the same name in a method.
System.out.println(counter + " " + lineStr);
counter++;
}
}
Note: Make sure you break your while loop, otherwise it will go into infinite loop.
You can't have multiple variable without the same name. You must rename one of your line variables.
When creating a scanner, you need to send in the input stream you want it to read from. System.in can server as this stream and it will read from your console. Your question though seems to indicate that you want to read from a file. If you indeed want to read from a file, you need to create the file you want to read from and send that file into the scanner to allow the scanner to read from that file.
Try:
public class Solution {
public static void main(String[] args) {
//create the File
File file = new File(filename);
//send the file into Scanner so it can read from the file
Scanner scanner = new Scanner(file);
//initialize the counter variable
int counter = 1;
//read in the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(counter +" "+ line);
counter++;
}
}
}
To read user input, you need to use System.in in your declaration of the line object in your code:
Scanner line = new Scanner(System.in);
int counter = 0; // Initialized out of loop.
while (line.hasNextLine()) {
String ln = line.nextLine();
System.out.println(counter +" "+ln);
counter++;
}

Java: Overwrite one character while copying a textfile

My current program reads a file and copies it to another directory, but I want it to change one single character to x, which is given by two ints for the number of the line and the number of the character in the line.
For example if int line = 5 and int char = 4, the fourth character in line five is changed to an x, the rest remains.
How can I add this to my program?
import java.io.*;
import java.util.Scanner;
public class copytest {
public static void main(String[] args) throws Exception {
readFile();
}
public static void readFile() throws Exception {
// Location of file to read
File file = new File("Old.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//System.out.println(line);
writeFile(line);
}
scanner.close();
System.out.println("File Copied");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File("New.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
}
Change your loop to:
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber) + wantedChar +
line.substring(charNumber);
}
}
writeFile(line);
i++;
}
Note that it will replace the char only if the line long enogth.
Ran Eldan has answered your Question, but I want to point out a couple of other major problems with your code:
You are violating Java's identifier style rules. Java class names should be "camel case" and the first character should be an uppercase letter; i.e.
public class copytest {
should be
public class CopyTest {
This is not just a random nit-pick. If you ignore these style rules, you are liable to get yourself into problem when one of your class names collides with a member or package name defined by your ... or someone else's code. The errors can be very hard to spot.
And of course, if you flout the style rules, you will get continual flak from other programmers when they need to read your code.
Your writeFile method is horribly inefficient. Each time you call it, you open the file, write a line and close it again. This results in at least 3 system calls for each line written. Syscall overheads are significant.
And in addition to being inefficient, you have the problem of dealing with existing output files when the program is run multiple times.
What you should do is open the file once at the start of the run, and use the same BufferedWriter throughout.

Reading certain sentences from datafile.txt in java

In my program, it reads a file called datafile.txt... inside the datafile.txt is a random 3 lines of words. What my program does is reads the file the user types in and then they can type in a Line # and Word # and it will tell them the word that is in that location.. for example..
What is the file to read from?
datafile.txt
Please enter the line number and word number (the first line is 1).
2 2
The word is: the
My problem is that my program reads the 3 lines in the txt doc as 0, 1 ,2 and the words start from 0. So to read the first word in the first line they would have to type 0,0 instead of 1,1. What I am trying to do is make it work so they can type 1,1 instead of 0,0. Not sure what my problem is right now, here is my code....
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class readingFile {
/**
* #param args
* #throws IOException
* #throws validException
*/
public static void main(String[] args) throws IOException, checkException
{
System.out.println("Enter file name: " );
Scanner keyboard = new Scanner(System.in);
BufferedReader inputStream = null;
ArrayList<String> file = new ArrayList<String>();
String fileName = keyboard.next();
System.out.println ("The file " + fileName +
" has the following lines below: ");
System.out.println();
try
{
inputStream = new BufferedReader(new FileReader(fileName));
ArrayList<String> lines = new ArrayList<String>();
while(true)
{
String line = inputStream.readLine();
if(line ==null)
{
break;
}
Scanner itemnize = new Scanner(line);
while(itemnize.hasNext())
{
lines.add(itemnize.next());
}
lines.addAll(lines);
System.out.println(lines+"\n");
}
System.out.println("Please enter the line number and word number");
int index1 = keyboard.nextInt();
int index = keyboard.nextInt();
System.out.println("The word is: "+ lines.get(index));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
}
inputStream.close();
}
private static void checkValid(ArrayList<String> items, int index) throws checkException
{
throw new checkException("Not Found");
}
}
The obvious solution to adapt 1-based user input to 0-based internal representation is to subtract one at some point. Seeing that you don't even use index1, writing
lines.get(index - 1)
isn't going to solve your problem completely. But I guess you can take it from there, and do something similar for the word index.
As I assume you are just learning to program I will point out 3 areas of improvement
Much like how mathematics has BIDMAS which determines the order of evaluation of an expression Java and other program languages evaluate statements in a particulate way. This means within the Parentheses of a function you may include a statment instead of a variable or constant. This will be evaluated with the result (or return) been passed into the called function. This is why MvG says you can do lines.get(index - 1)
Not all exceptions you should consider and plan around will the compiler inform you about. For example in your code an invalid input for line number or word number is entered you will get a Runtime Exception (array index out of bound)
Naming of variables should be useful, you have index and index1. What's the difference? I assume from reading your code one should be the user selected index of the line number and the second should be the index of the word on said line. May I suggest requestedLineIndex and requestedWordIndex.
On a final note this is not a usual StackOverflow question hence why your question has been 'voted down'. If you are learning as part of a course is there a course forum or Virtual Learning Environment (VLE) you can post questions on? The support of your peers at the same level of learning tends to help with exploring the basics of a language.

Categories