Jump to content
  • Advertisement
Sign in to follow this  
Enerjak

C# Reading individual data from files similar to Java

Recommended Posts

Posted (edited)

I've recently begun to learn C#. As you can see from this code snippet: 

Scanner file = new Scanner(new File("hashValues.txt"));
		
String miningDay = "";
String currency = "";
double netPayOut = 0.0;
String i = "";
String walletID = "";
Array hashValues;
while(file.hasNext())
{
	miningDay = file.next();
	currency = file.next();
	netPayOut = file.nextDouble();
	i = file.next();
	walletID = file.next();
}

Java has a class called Scanner which allows you to open a file through the file class. The Scanner class has functions to read individual strings, as well as int and double data types. Does C# have something similar to this? I tried to do something like this, but it doesn't really work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.IO;

namespace Mod3_Lab1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader addressBook = null;

            String Name = "";
            String Address = "";
            try
            {
                addressBook = new StreamReader("address_book.txt");

                while(!addressBook.EndOfStream)
                {
                    Name = addressBook.ReadLine();
                    Address = addressBook.ReadLine();
                }

                addressBook.Close();

                Console.WriteLine("Name: " + Name);
                Console.WriteLine("Address: " + Address);
            }
            catch(FileNotFoundException)
            { 

            }
        }
    }
}

Here is the output: 

a17ea39570.png

Edited by Enerjak

Share this post


Link to post
Share on other sites
Advertisement

are you sure the name and address are on separate lines?

 Can you show us the contents of address_book.txt?

Share this post


Link to post
Share on other sites
Posted (edited)
18 minutes ago, ChaosEngine said:

are you sure the name and address are on separate lines?

 Can you show us the contents of address_book.txt?

No, Name and address are not on separate lines. 

Quote

Robert Holidy 401 bridge Avenue

However, the code I wrote here:

package Def;

import java.io.*;
import java.util.Scanner;

import javax.swing.JOptionPane;
public class Application 
{
	public void main(String[] ages)
	{
		
		try
		{
			Scanner scan = new Scanner(new File("Address_book.txt"));
			String Name = "";
			String Address = "";
		
			while(scan.hasNext())
			{
				Name = scan.next();
				Address = scan.next();
			}
			
			JOptionPane.showMessageDialog(null, Name);
			scan.close();
		}
		catch(FileNotFoundException e)
		{
			
		}
	}
}

This should load Address_book.txt - which for some reason it doesn't, but that's another problem all together. 

Edited by Enerjak

Share this post


Link to post
Share on other sites
6 hours ago, Enerjak said:

No, Name and address are not on separate lines

Ok, well your code is expecting them on separate lines.

// reads one line
Name = addressBook.ReadLine();
// reads next line
Address = addressBook.ReadLine();

if you change address_book.txt to something like 

Quote

Robert Holidy

401 bridge Avenue

1

it will work.

The other problem is that if you have more than one line, you will only store the last line in the Name and Address strings.

If you want to put them on one line, you will need some kind of delimiter (a tab character, or a | ) to say when the name ends and the address begins (you could just assume that the name is the first two words, but then you're stuffed if someone puts a middle name or initial).

I don't know much about the Scanner class, but a cursory google tells me your java code won't work either.

Share this post


Link to post
Share on other sites
2 hours ago, ChaosEngine said:

Ok, well your code is expecting them on separate lines.


// reads one line
Name = addressBook.ReadLine();
// reads next line
Address = addressBook.ReadLine();

if you change address_book.txt to something like 

it will work.

The other problem is that if you have more than one line, you will only store the last line in the Name and Address strings.

If you want to put them on one line, you will need some kind of delimiter (a tab character, or a | ) to say when the name ends and the address begins (you could just assume that the name is the first two words, but then you're stuffed if someone puts a middle name or initial).

I don't know much about the Scanner class, but a cursory google tells me your java code won't work either.

I got the code in Java to work. Here is the fixed code:

package address_book;

import java.io.*;
import java.util.*;
import javax.swing.*;

public class application 
{
	public static void main(String[] args)
	{
		Scanner file = null;
		person per = null;
		try
		{
			file = new Scanner(new File("address_book.txt"));
			
			String firstName = "";
			String lastName = "";
			String address = "";
			
			while(file.hasNext())
			{
				firstName = file.next();
				lastName = file.next();
				address = file.nextLine();
				per = new person(firstName, lastName, address);
			}
			file.close();
			
			System.out.println(per.getFirstName() + " " + per.getLastName() + " " + per.getAddress());
		}
		catch(FileNotFoundException e)
		{
			
		}
	}
}

This is what it outputs:

0f3cd9c5fc.png

And here is the address book file again just for reference:

Quote

Robert Holiday 500 bridge Avenue

As you can see from the fixed code above, I have made three string variables, firstName, lastName, and address. In order to get the first name from the file, I used Scanner.next(), which reads the string "Robert." Scanner.next() only reads one string until there is a space. Next I read in the last name using another Scanner.next() to get the last name. The Scanner.nextline() gets the rest of the line in the file - which is the address. 

Share this post


Link to post
Share on other sites

Again, that assumes that your name will always be two words separated by a space. What happens if someone adds John F. Kennedy? or Carrie Anne Moss?

Who is generating the address_book.txt file? If it's you, you might consider adding a delimiter.

 

 

Share this post


Link to post
Share on other sites
12 minutes ago, ChaosEngine said:

Again, that assumes that your name will always be two words separated by a space. What happens if someone adds John F. Kennedy? or Carrie Anne Moss?

Who is generating the address_book.txt file? If it's you, you might consider adding a delimiter.

 

 

I found this on Google: https://stackoverflow.com/questions/24041113/error-1-inconsistent-accessibility-return-type-is-less-accessible-than-method It shows how to split the lines into an array using a delimiter - like you said I should use. I should have searched more than make a post on it. Thanks for your help. 

Share this post


Link to post
Share on other sites
2 hours ago, Enerjak said:

I found this on Google: https://stackoverflow.com/questions/24041113/error-1-inconsistent-accessibility-return-type-is-less-accessible-than-method It shows how to split the lines into an array using a delimiter - like you said I should use. I should have searched more than make a post on it. Thanks for your help. 

Are you sure that's the right link? I don't see anything about splitting strings there. 

but yeah, basically you want the string.Split method. 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Similar Content

    • By Hellados
      Hello guys, my name is Giorgi and i'm newbie game developer i'm learning Pixel art and after pixel art  i want learn C# and don't know how and where start i'm bad with programming language and know only HTML/CSS
    • By D34DPOOL
      Edit Your Profile D34DPOOL 0 Threads 0 Updates 0 Messages Network Mod DB GameFront Sign Out Add jobEdit jobDeleteC# Programmer for a Unity FPS at Anywhere   Programmers located Anywhere.
      Posted by D34DPOOL on May 20th, 2018
      Hello, my name is Mason, and I've been working on a Quake style arena shooter about destroying boxes on and off for about a year now. I have a proof of concept with all of the basic features, but as an artist with little programming skill I've reached the end of my abilities as a programmer haha. I need someone to help fix bugs, optomize code, and to implent new features into the game. As a programmer you will have creative freedom to suggest new features and modes to add into the game if you choose to, I'm usually very open to suggestions :).
      What is required:
      Skill using C#
      Experience with Unity
      Experience using UNET (since it is a multiplayer game), or the effort and ability to learn it
      Compensation:
      Since the game currently has no funding, we can split whatever revenue the game makes in the future. However if you would perfer I can create 2D and/or 3D assets for whatever you need in return for your time and work.
      It's a very open and chill enviornment, where you'll have relative creative freedom. I hope you are interested in joining the team, and have a good day!
       
      To apply email me at mangemason@yahoo.com
    • By Andrew Parkes
      I am a talented 2D/3D artist with 3 years animation working experience and a Degree in Illustration and Animation. I have won a world-wide art competition hosted by SFX magazine and am looking to develop a survival game. I have some knowledge of C sharp and have notes for a survival based game with flexible storyline and PVP. Looking for developers to team up with. I can create models, animations and artwork and I have beginner knowledge of C sharp with Unity. The idea is Inventory menu based gameplay and is inspired by games like DAYZ.
      Here is some early sci-fi concept art to give you an idea of the work level. Hope to work with like minded people and create something special. email me andrewparkesanim@gmail.com.
      Developers who share the same passion please contact me, or if you have a similar project and want me to join your team email me. 
      Many thanks, Andrew.

    • By mike44
      The reference assemblies for framework ".NETFramework,Version=v3.5" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend.

      Hi
      what to do with the above error in ms code/Unity3d Project on Ubuntu 18.04? I've installed it like:
      https://www.microsoft.com/net/learn/...ux/ubuntu18-04
      Many thanks
    • By Dave Haylett
      Hi.
      I have pulled in five NuGet packages for my Visual Studio 2017 project, however when I build the project, VS spits out 10 .DLL and .XML files in the root of the binary folder, to do with the packages. Can't I shove them into a \packages folder so the user doesn't see these ugly resources next to the .exe file?
      I've Googled moving the packages but the only responses seem to be around moving the installation folder of the NuGet packages on the local machine, as opposed to where VS builds them to.
    • By MoreLion
      hey all! We are looking for members for our Unity horror game! 
      Here’s the story:
      After a deadly virus plunges the world into chaos killing 85% of the human population there are now what they call “zones” these zones are watched very closely by the surviving government, people are checked every day for the virus, even if you touch the spit or any human waste or fluids of the victim who is infected, you will die. But one day, people in the west zone start to go missing, 1 woman goes outside the walls to uncover the mystery, is there more to the virus than meets the eye?, That is where your story starts.
      This game is not a long development game, I have loads other game ideas,
      I will also allow you to have a bit of creative freedom if you wish to add or share a idea!
      And no, it’s not a zombie game lol I feel like zombie games are too generic, in this game you will encounter terrifying beasts!
      There is some concept art one of our concept artists have made
      If interested email liondude12@gmail.com
    • By Victor Rodriguez
      Hi there! Is the first time that I'm posting here so I'm sorry if I'm doing it wrong ha. 
      So here it comes, my doubt is, I'm doing a game with different levels, each of these levels in one different scene. Each scene contains to cameras that you can change pressing a button. Everything works fine. 
      The only problem is that I would like it to look a bit more professional, and I would like that if you finish the level with camera2, the next level start the same way. I've been thinking about using dontdestroyonloadon both cameras, but obviously this cameras need to be attached to the player to make the movement work, what do you recommend? Sorry If I've explained it in a messy way, and feel free to dm me for anything. Thanks in advance! 
    • By MoreLion
      The Standing

      Description:
      
      After a deadly virus plunges the world into chaos killing 85% of the human population there are now what they call “zones” these zones are watched very closely by the surviving government, people are checked every day for the virus, even if you touch the spit or any human waste or fluids of the victim who is infected, you will die. But one day, people in the west zone start to go missing, 1 woman goes outside the walls to uncover the mystery, is there more to the virus than meets the eye?, That is where your story starts.

      Includes:
      A Terrifying Adventure. A Ton Of Lore To Explore. First person Shooter view point. Kill, or be killed.  

      Team Name:
      Team Rebound

      Team Structure:
      Rio Dakota (Project Creator)
      Lead,Game Design,Writer
      Bastaird (Concept Artist)
      Kat (Main Character Actor)
      Voice Actor


      Previous Work:
      Project FreeFall - Unknown If Released

      Talent Required:
      Unity Programmer(3)
      Must know how to work with other Members. must know how to use unity engine Must know how to work with modellers etc Required:Must Know C#  
       3D Artist (3D Animators, Hardsurface modeller etc etc)(3)
      Ability to export Models Experience with Unity toolset a bonus. Expected to create additional props & hard surfaces for use in environments.
      3D Character Artist (1)
      Experience with Maya Or blender Or Cinema4D required. Experience with Unity toolset is a bonus. Required to create, rig and animate player, npcs & monsters. Contact:
      E-mail:Liondude12@gmail.com
      Discord:riobio55#1958
    • By ethancodes
      Hopefully this is an easy fix, but I'm getting an error for trying to access the Rigidbody2D on my LevelManager gameobject. Now, I would understand this no problem, except I'm not trying to access my LevelManager anywhere. At least not intentionally. I found the line of code that is causing the error is here:
      void Awake () { this.GetComponent<Rigidbody2D> ().velocity = new Vector2 (2f, 10f); } This is a method on my BasePickUp abstract class. This class has several child classes that are implemented on a few pick ups. I tried changing 'this' to 'gameObject', but got the same results. And the code is doing what I want. If I take it out, the pickups just fall slowly down the screen, put the code back in and the pickups shoot off in a certain direction just like I want. So it is working, but it's also causing this weird error. Any ideas?
    • By ethancodes
      I'm trying to make a pick up that add's 4 specials "shots" when it gets picked up. The game is a brick breaker style game and when the ball hits the paddle, if we have any of the special shots left, the original ball should bounce back like normal, but there should be 7 additional balls instantiating in quick succession and those balls should all follow the first ball directly. As the balls hit objects, either bricks, walls, or anything else, they will be destroyed. The last remaining ball will become the new mainBall and will continue the gameplay like normal. All the additional balls that spawn should spawn right from the paddle and then shoot outward. I'm not so concerned about them hitting the exact same place as the first ball, as I am with them moving the same way. So if the player very quickly moves the paddle after impact, the balls may fire in a scattered line.
       
      So far, I have come up with the idea of having a Ball class that will be attached to each Ball instance. This should have basic ball behavior or attributes attached to it such as Speed, and then I would have a BallManager class that handles any modifications, spawning, destroying of balls. But I'm not sure what exactly needs to be in the Ball class and what need to be in the BallManager class. And I'm not sure how to handle the spawning and destroying, etc. I've tried to write several different forms of pseudocode to try to come up with something that makes sense, but I keep running into problems. Any ideas?
  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
      631359
    • Total Posts
      2999545
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!