I am trying to print some data from a text file, data in file would be something like this
user1.txt
1,1412.0 2,345.0 3,500.0 4,234.0 5
**As somebody saying the text file may contain r ** i will provide link for my user1.txt file https://drive.google.com/file/d/1aLCFQhduyt2e3VuBSgR-KJyKgmlz5gO0/view?usp=sharing
Code:
public class Main { public static void main(String[] args) throws IOException { // write your code here File f = new File("D:\Fit\user1.txt"); Scanner sc = new Scanner(f); Scanner csc = new Scanner(f); sc.useDelimiter("[,n]"); while (sc.hasNext()){ String d= sc.next(); try { //I only need to print upto 4,234.0 so using a try block String c = sc.next(); //to skip the last line in text file which is "5" System.out.println("Day"+d+":"+c+" cal"); } catch (Exception e){ break; } } } }
My problem is, the output that i need
Day1:1412.0 cal Day2:345.0 cal Day3:500.0 cal Day4:234.0 cal
But the output it gives is
cal cal cal cal cal
If i used System.out.println("Day"+d+":"+c);
it gives the output as normal like
output:
Day1:1412.0 Day2:345.0 Day3:500.0 Day4:234.0
I dunno why it only prints “cal” if I used System.out.println("Day"+d+":"+c+" cal")
Advertisement
Answer
change String c = sc.next();
to String c = sc.nextLine().substring(1);
you will get output:
Day1:1412.0 cal Day2:345.0 cal Day3:500.0 cal Day4:234.0 cal