How to print txt file with file numbers using I/O? - java

i am printing a .txt file using the Scanner and I want to print the file with line numbers. here is my code. My problem is that the line numbers aren't incrementing.
import java.util.*;
import java.io.*;
public class List
{
public static void main(String[] args) throws IOException
{
int line =1;
File f = new File("src/List.txt");
Scanner sc = new Scanner(f);
while(sc.hasNext())
{
int num = 1;
System.out.print(num);
System.out.println(sc.nextLine());
num++;
}
}
}
Output:
1Bird
1Dog
1Cat
1Elephant
1Tiger
1Zebra
Expected Output:
1 Bird
2 Dog
3 Cat
4 Elephant
5 Tiger
6 Zebra

Take int num = 1 and place it out side of the loop...
int num = 1;
while(sc.hasNext())
{
System.out.print(num);
System.out.print(" "); // Separate the line number from the text
System.out.println(sc.nextLine());
num++;
}
This way it won't be reset every time the loop restarts...

Your bug seems to be mixing up line and num in the body of the loop, but I would also recommend you use formatted output and something like -
while(sc.hasNextLine()) {
System.out.printf("%d %s%n", line++, sc.nextLine());
}
The format String "%d %s%n" describes a number then a space then a String and then new-line. Next, perform a post-increment on line. Finally, get the nextLine() from the Scanner.

You should remove
int num = 1;
because this will ALWAYS set num BACK TO 1 while it hasNext. This is why the line number won't increment.
After deleting that, also delete
num++;
because there is no more num variable. Replace that with:
line++;
I hope this helps!

Related

How would I go about using an integer delimiter? (Java)

So I am trying to read a file using a scanner. This file contains data where there are two towns, and the distance between them follows them on each line. So like this:
Ebor,Guyra,90
I am trying to get each town individual, allowing for duplicates. This is what I have so far:
// Create scanner for file for data
Scanner scanner = new Scanner(new File(file)).useDelimiter("(\\p{javaWhitespace}|\\.|,)+");
// First, count total number of elements in data set
int dataCount = 0;
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.println();
dataCount++;
}
Right now, the program prints out each piece of information, whether it is a town name, or an integer value. Like so:
Ebor
Guyra
90
How can I make it so I have an output like this for each line:
Ebor
Guyra
Thank you!
Assuming well-formed input, just modify the loop as:
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.print(scanner.next());
System.out.println();
scanner.next();
dataCount += 3;
}
Otherwise, if the input is not well-formed, check with hasNext() before each next() call if you need to break the loop there.
Try it that way:
Scanner scanner = new Scanner(new File(file));
int dataCount = 0;
while(scanner.hasNext())
{
String[] line = scanner.nextLine().split(",");
for(String e : line) {
if (!e.matches("-?\\d+")) System.out.println(e);;
}
System.out.println();
dataCount++;
}
}
We will go line by line, split it to array and check with regular expression if it is integer.
-? stays for negative sign, could have none or one
\\d+ stays for one or more digits
Example input:
Ebor,Guyra,90
Warsaw,Paris,1000
Output:
Ebor
Guyra
Warsaw
Paris
I wrote a method called intParsable:
public static boolean intParsable(String str)
{
int n = -1;
try
{
n = Integer.parseInt(str);
}
catch(Exception e) {}
return n != -1;
}
Then in your while loop I would have:
String input = scanner.next();
if(!intParsable(input))
{
System.out.print(input);
System.out.println();
dataCount++;
}

scanner + loop single line

Ask the user to enter in a number, then you can print out the number of many * on the screen without spaces or newlines. You may use your Scanner object in numbers 5, 6 and 9 also.
Input:
7
Output:
*******
I can do this but I can't do it in a single line all the astericks
import java.util.Scanner;
class {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x;
int i;
System.out.println("Enter a number:");
x = scan.nextInt();
for (i = 0; i < x; i++) {
System.out.println("*");
}
}
}
You can use a for-loop like so changing println to just print so you print the * on the same line:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number:");
int inputNumber = sc.nextInt();
for(int i=0;i<inputNumber;i++) {
System.out.print('*');
}
}
}
Try it here!
Note: You can initialize i within the for-loop and don't need to declare it beforehand
It's my first response i hope to help you...
Try
System.out.print("*");
if you use
System.out.println("*");
Your program will do a line jump...
To print all the asterisks in a single line, use print instead of println:
Scanner scan = new Scanner(System.in);
int x;
int i;
System.out.println("Enter a number:");
x = scan.nextInt();
for (i = 0; i < x; i++) {
System.out.print("*"); // <- note the difference here!
}
Why? Let's look at the docs:
print(String):
Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
println(String):
Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
So println(String) calls print(String) then println(). What does println() do?
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
Now you see the difference! println(String) prints a new line after it prints the string while print(String) does not!
Here's a cleaned up version of your code:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
int x = scan.nextInt();
for (int i = 0; i < x; i++) {
System.out.print("*");
}
You should to use
System.out.print("*");
and not
System.out.println("*");
Because println return to line and print not.
Hope this can help you.
Note
Your class need a name in your question you do :
class {
and this wrong in java, so you need to declare your class like this:
class nameClass {
//Your code
}
Take a look here :
Getting Started
and here:
Arrays

Printing an input's digits each in a new line

First of all, i just started programming with Java so i'm really a noob :P
Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line.
for example, if the user gave 12345, the program will give:
1
2
3
4
5
each number in a new line.
The statements i will be using is IF statement and the loops and operators ofcourse.
I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.
So can anyone help me or give me any ideas?
import java.util.Scanner;
public class NewLineForDigit {
public static void main(String[] args) {
System.out.print("Please, enter any integer: ");
Scanner sc = new Scanner(System.in);
String intString = sc.next();
for (char digit : intString.toCharArray()) {
System.out.println(digit);
}
}
}
Given the assignment your instructor gave you, can you convert the int into a String? With the input as a String, you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:
String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
System.out.println( input.charAt(i) );
How about using a Scanner to get the users input as an int and converting that int to a String using valueOf. Lastly loop over the String to get the individual digits converting them back to int's from char's :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a Integer:");
int input = sc.nextInt();
String stringInput = String.valueOf(input);
for(int i = 0; i < stringInput.length(); i++) {
int j = Character.digit(stringInput.charAt(i), 10);
System.out.println(j);
}
}
}
Try it here!

Array split not giving expected output

Sir i am trying to split array[i] and storing that into another array but it is not working.
Here is my code
import java.util.Scanner;
public class prog1 {
public static void main (String [] args){
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String arr1[] = new String [a];
for (int i=0;i<a;i++) {
arr1[i] = input.nextLine();
}
for (int i=0;i<a;i++) {
String temp[] = arr1[i].split("\\+");
System.out.println(temp.length);
System.out.println(temp[0]);
}
}
}
Sample input :
1
arka + xyz
Expected Output :
2
arka
But the output which i am getting
1
<blank>
I am new in java . would you please help me to solve this problem as well as tell me why i am facing this problem.
You only read an int with nextInt() and you didn't consume the end of the first line before reading additional lines in your for loop, so the first iteration of the for loop reads the end of the first line, not the second line.
Chomp the end of the first line before starting your for loop:
String chomp = input.nextLine();
for(int i=0;i<a;i++){
// Then read the following lines here.
The problem is when you hit enter after entering a number it is read as the next line.
One way to solve this is to add input.next(); right after int a = input.nextInt(); which will read the return character. I think then the application will behave as you expect.
Alternatively you could read the number like this.
int a = Integer.parseInt(input.nextLine());

writes several line to standard out put in reverse order

I want to write a program in java that takes all the lines input to standard input and writes them to standard output in reverse order.
this is may code but it has an error and I can't understand where is the problem
(In this program at first I ask for the number of lines and then save it in 'n'.)
any help?
thanks in advance
package getLine;
import java.util.Scanner;
public class S {
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("how many lines do you want to enter");
int n= s.nextInt();
String [] str;
str= new String[n];
for(int i=0;i<n;i++)
str[i]=s.nextLine();
for(int i=n;i>=0;i--)
System.out.println(str[i]);
}
}
Why don't you use a Stack<String> to buffer the lines? Then simply pop every line and output it.
Following is the code with output:
import java.util.Scanner;
public class S {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("how many lines do you want to enter");
int n = s.nextInt();
System.out.println("I want to enter " + n + " lines ");
n = n + 1;
String[] str;
str = new String[n];
int count = 0;
for (int i = 0; i < n; i++) {
str[i] = s.nextLine();
System.out.println(str[i]);
count++;
}
if (count == n) {
System.out.println("Reversed output");
for (int i = n - 1; i >= 0; i--) {
System.out.println(str[i]);
}
}
}
Output:
how many lines do you want to enter
2
I want to enter 2 lines
1
1
2
2
Reversed output
2
1
for(int i=n-1;i>=0;i--)
System.out.println(str[i]);
Do you get ArrayIndexOutOfBoundsException? The error lies here:
for(int i=n;i>=0;i--)
System.out.println(str[i]);
In the first step of that loop you attempt to print str[n], which doesn't exist.
Your array consists of n elements numbered from 0 to n-1.
The proper code is:
for(int i = n - 1; i >= 0; i--)
System.out.println(str[i]);
You need to start from n-1 because the maximum index accessible in an array is array.length-1.
for(int i=n-1;i>=0;i--){
Also you need to make this change:-
int n= Integer.parseInt(s.nextLine());
s.nextInt() reads the next integer all right, but the enter you hit after that, is consumed as the first element of your array. To avoid that, you can do as I mentioned above.
You don't have to do much to handle this, just replace your line in a code by the following code-
int n = s.nextInt()+1;

Categories

Resources