Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Hi, I am new to Java and struggling a bit with Javaio, how can I change this program to read from a .txt file? The

Hi, I am new to Java and struggling a bit with Javaio, how can I change this program to read from a .txt file? The file would contain something basic like:

int x; int y;

int sum = x + y;

sout(sum);

I want it to be able to read all the lines in the file and split it into tokens.

import java.util.Scanner; public class NewClass { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String line = ""; System.out.println("Enter # of lines "); String input[] = new String[scan.nextInt()]; //Creates a string called input String store[]; int h; System.out.println("Give your input"); scan.nextLine(); for (h = 0; h < input.length; h++) { input[h] = scan.nextLine(); line = line + input[h]; //Takes the input from the user and concatenates into a single string called line. } int flag = 1; store = line.split(" ");//Separate the tokens using the split function & save them in store array int len = store.length; int no1 = 1; String s[] = new String[100]; s[0] = "%"; int n = 0; System.out.println(" "); for (int k = 0; k < len; k++){ switch (store[k]){ //Switch loop identifies the different tokens case "int": System.out.println(""); break; case "float": System.out.println(""); break; case "char": System.out.println(""); break; case "double": System.out.println(""); break; case ",": System.out.println(""); break; case";": System.out.println(""); break; case"+": System.out.println(""); break; case"-": System.out.println(""); break; case"/": System.out.println(""); break; case"%": System.out.println(""); break; case"*": System.out.println(""); break; case"=": System.out.println(""); break; default: String b = store[k]; char ch[] = b.toCharArray(); if (Character.isDigit(ch[0])){ System.out.println(""); } else { if (Character.isLetter(ch[0])){ flag = 1; for (int u = 0; u < no1; u++){ if(s[u].equals(store[k])){ n = u; flag = 0; } } if (flag != 0){ s[no1] = store[k]; n = no1; no1++; } } } } } System.out.println(" "); System.out.println("No of tokens: " + store.length); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Time Series Databases New Ways To Store And Access Data

Authors: Ted Dunning, Ellen Friedman

1st Edition

1491914726, 978-1491914724

More Books

Students also viewed these Databases questions

Question

5. Arranging for the training facility and room.

Answered: 1 week ago

Question

1. Discuss the five types of learner outcomes.

Answered: 1 week ago