I am looking to manipulate a text file through frequency by letter order. In my program there is a method I'm not sure how to start. I'd like to get an output something like:
Letter / Count
1 A 6 ***
2 B 8 ****
3 C 6 ***
(etc.)
To which 6 names begin with A, 8 with B, and 6 with C.
Then an '*' for every 2 count.
My practice problem is actually using a text file with 90000 names and a different '*' count, but an example code and explanation of why it works would be greatly appreciated for my study.
Here's the beginning of my program, but like I said I'm not sure how to start this method whatsoever.
import javax.swing.JOptionPane;
import java.io.*;
public class P03Census {
String rec;
int ctr = 0;
public static void main(String[] args)throws IOException {
Object result = JOptionPane.showInputDialog(null, "Enter a file name\n(1990 to 2000)\nadd extension",
"Taylor Daggett", JOptionPane.PLAIN_MESSAGE);
String textDoc = (String) result;
File file = new File(textDoc);
System.out.println("-----------------------------------------------------------------------------------------");
System.out.println("File name: " +
file);
if (!textDoc.endsWith(".txt")) {
System.out.println("Usage: This is not a text file!");
System.exit(0);
} else if (!file.exists()) {
System.out.println("File not found!");
System.exit(0);
}
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String rec;
int lines = 0;
int i;
while((rec = br.readLine()) != null){
lines++;
}
System.out.println("Record count:"+lines);
System.out.println("------------------------------------------------------------------------------------------");
}
}
Here's an algorithm that would do what you want, it exploits the fact you can use char variables as int:
First, create an array int[] letterCount = new int[26], which you will use to count the letters.
Then, inside the body of your main while loop, convert the string rec into an array String[] where every element is a name. If, in your input file, the names are always separated by the same char (like whitespace for example), you could use String[] names = rec.split(" ").
Next, run through that names in a for loop, and check the first letter of each name: char firstLetter = names[i].charAt(0). And use it to increase the count of that letter by one, in the array letterCount: letterCount[firstLetter - 'a']++;
At the end of the loop, letterCount should have the right count. Note that if you file contains capital letters, you have to call rec.toLowerCase(), at the start of the body of the loop, otherwise you will get out of bounds error, when trying to call letterCount[firstLetter - 'a'], or if all names start with upper case, then just replace by letterCount[firstLetter - 'A']
Related
Task is to read an article of text from outside file and put each word (no signs) into and Array List as a separate String.
Although I´m sure my path is correct and readable(I can for example perform character count), no matter what I do my Array List of words from that article comes out as empty. I may be struggling with a way how to separate words from each other and other signs. Also with storing the result of reading.
I´ve been googling for the last 2 hours and reading similar answers here but no success. So decided for the first time to ask a question.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import org.w3c.dom.Text;
public class PlaceForErrors {
public static void main(String[] args) {
Scanner scan = null;
try {
scan = new Scanner(new File("\\Users\\marga\\Desktop\\objekt program\\oo2021\\w05_kontrolltoo1\\textHere.txt")).useDelimiter(" \\$ |[\\r\\n]+");
String token1 = "";
ArrayList<String> text = new ArrayList<String>();
while (scan.hasNext()) {
token1 = scan.next();
text.add(token1);
}
String[] textArray = text.toArray(new String[0]);
for(String element : textArray){
System.out.println(element);
}
//Controlling if the ArrayList is empty and it is
boolean tellme = text.isEmpty();
System.out.println(tellme);
} catch (FileNotFoundException exception) {
System.out.println(exception);
}
finally{
scan.close();
}
}
}
String[] textArray = text.toArray(new String[0]);
This line is your problem. You're trying to allocate the ArrayList into a String array of size 0, resulting in it appearing empty.
I would modify the array declaration to initialize using the ArrayList size, like so:
String[] textArray = text.toArray(new String[text.size()]);
Then you can see if your token delimiter works.
Quick recap of your steps
Your program does a lot. I counted 9 steps:
opens a (text) file as (text) input-stream to read from
create a scanner for tokens from this input-stream using a regular-expression as delimiter (= tokenizer)
scan for and iterate over each subsequent token (if any found) using a while-loop
each of this iteration adds the token to a list
if no more tokens, then iteration ends (or never started!): converts the list to array
loop over each array element using a for-each-loop and print it
check if originally collected list is empty and print true or false
catch the exception if file was not found and print the it
finally close any opened resources: the file that was read from
Now let's start to look for the step where something potentially could go wrong: the places for errors 😏️
Analysis: What can go wrong?
Look at the listed steps above and think of each from a what-could-go-wrong perspective, a quick check list (not correlated to the step-numbers above!):
Can your text-file be found, does it exist and is readable? Yes, otherwise any IOException like FileNotFoundException would have been thrown and printed.
Is the opened file empty with a size of 0 bytes? You can check using:
File textFile = new File("\\Users\\marga\\Desktop\\objekt program\\oo2021\\w05_kontrolltoo1\\textHere.txt");
System.out.println( "File size: " + textFile.length() );
// before passing the extracted file-variable to scanner
scan = new Scanner( textFile ).useDelimiter(" \\$ |[\\r\\n]+");
Does the delimiter/regex properly split/tokenize an example input string? Try:
// Just a separate test: same delimiter, with test-input
String delimiterRegex = " \\$ |[\\r\\n]+";
String testInput = " $ Hello\r\nWorld !\n\nBye.";
// so we create a new scanner
Scanner testScanner = new Scanner( testInput ).useDelimiter(delimiterRegex);
int tokenCount = 0;
while( testScanner.hasNext() ) {
tokenCount++;
System.out.println("Token " + tokenCount + ": " + testScanner.next() );
}
testScanner.close();
Should print 3 tokens (Hello, World !, Bye.) on 3 lines in console. The special sequence $ (space-dollar-space), any \n or \r (newline or carriage-return) are omitted and have split the tokens.
We should check the list directly after the while-loop:
// Not only checking if the ArrayList is empty, but its size (is 0 if empty)
System.out.println("Scanned tokens in list: " + text.size());
If it is empty, then we neither need to fill the array, nor loop to print will start (because nothing to loop).
Hope these explanations help you to perform the analysis (debugging/testing) yourself.
Let me know if it helped you to catch the issue.
Takeaway: Divide and conquer!
Why did I count the steps, above? Because all are potential places for errors.
In developer jargon we also say this main method of class PlaceForErrors has many responsibilities: counted 9.
And there is a golden principle called Single Responsibility Principle (SRP).
Put simply: It is always good to split a large problem or program (here: your large main method) into smaller pieces. These smaller pieces are easier to work with (mentally), easier to test, easier to debug if errors or unexpected happens. Divide & conquer!
If it works, start improving
You can split up this long method doing 9 steps into smaller methods.
Benefit: each method can be tested in isolation, like the testScanner.
If your program finally works as expected and your manual test went green.
Then you should post the working code to the sister-site: CodeReview.
Be curious and ask again, e.g. how to split up the methods, how to make testable, etc.
You'll get lot's of experienced advise on how to improve it even more.
Thank you for your input everyone!
Regarding the code, I went and checked everything step by step and on the way learned more about delimiters and scanner. I fixed my delimiter and everything worked just fine now.
Beside the fact that I made a newbie mistake and didn´t show the full code, as I though it would take away the attention from the main problem. I had two conflicting scanners in my main function(one I showed you and the other one was scanning again and counting letters A). And they both worked great separately(when one or the other is commented out), but refused to work together. So I found a way to combine them and use scanner only once. I will share my full code for reference now.
I learned my mistake, and will provide the my full code always in the future.
If someone is curious the full task was the following:
Read the text from a separate file using scanner and store it in an Array List.
Count how many letters "A" (small or big) there were and how big of % they made out of all the letters in the text.
Count how many words had one letter A, two letters A in them, etc.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Trying {
public static void main(String[] args) {
Scanner scan = null;
try {
//SCANNING FILE AND CREATING AN ARRAYLIST
scan = new Scanner(new File("\\Users\\marga\\Desktop\\objekt program\\oo2021\\w05_kontrolltoo1\\textHere.txt")).useDelimiter("[.,:;()?!\"\\s]+");
int aCount = 0;
int letterCount =0;
String token1 = "";
int wordWithAtLeastOneA = 0;
int wordWithA = 0;
int word1A = 0;
int word2A = 0;
int word3A = 0;
int word4OrMoreA = 0;
ArrayList<String> text = new ArrayList<String>();
// SCANNING EVERY WORD INTO AN ARRAY LIST
while(scan.hasNext()){
token1 = scan.next();
text.add(token1);
}
System.out.println("Amount of words in the scanned list is : " + text.size());
//COUNTING HOW MANY LETTERS 'A' TEXT HAS
for(String element : text){
for (int i=0;i<=element.length()-1;i++){
if (element.charAt(i) == 'A' || element.charAt(i) == 'a') {
aCount++;
}
}
}
System.out.println("There are "+aCount+" letters 'A'. ");
//HOW MANY LETTERS IN TOTAL TEXT HAS
for(String element : text){
for (int i=0;i<=element.length()-1;i++){
letterCount++;
}
}
//COUNTING HOW MANY WORDS HAVE 'A' LETTER IN THEM
for(String element : text){
for (int i=0;i<=element.length()-1;i++){
if (element.charAt(i) == 'A' || element.charAt(i) == 'a') {
wordWithAtLeastOneA++;;
break;
}
}
}
System.out.println("There are "+wordWithAtLeastOneA+" words that have at least one letter 'A' in them.");
System.out.println();
//COUNTING NUMBER OF WORDS THAT HAVE 1/2/3 or more 'A' LETTER IN THEM
for(String element : text){
wordWithA = 0;
for (int i=0;i<=element.length()-1;i++){
if (element.charAt(i) == 'A' || element.charAt(i) == 'a') {
wordWithA++;
if(wordWithA == 1){
word1A++;
}else if (wordWithA == 2){
word2A++;
}else if (wordWithA == 3){
word3A++;
}else if (wordWithA >= 4){
word4OrMoreA++;
}
}
}
}
System.out.println("There were "+ word1A+ " words, that had one letter 'A' in them." );
System.out.println("There were "+ word2A+ " words, that had two letters 'A' in them." );
System.out.println("There were "+ word3A+ " words, that had three letters 'A' in them." );
System.out.println("There were "+ word4OrMoreA+ " words, that had 4 or more letters 'A' in them." );
//COUNTING HOW MANY LETTERS THERE ARE IN TOTAL, COMPARE TO NUMBER OF "A" LETTERS
int percentOfA = aCount*100/letterCount;
System.out.println();
System.out.println("The entire number of letters is "+ letterCount+" and letter 'A' makes " + percentOfA+ "% out of them or " +aCount+ " letters.");
// for(String element : textArray){
// System.out.println(element);
// }
} catch (FileNotFoundException exception) {
System.out.println(exception);
}
finally{
scan.close();
}
}
}
And the text is:
Computer programming is an enormously flexible tool that you can use to do amazing things that are otherwise either manual and laborsome or are just impossible.
If you are using a smartphone, a chat app or if you are unlocking your car with the push of a button,
then you must know that all these things are using some kind of programming.
You are already immersed in the programs of different types.
In fact, software is running your life. What if you learn and start running these programs according to your will?
And the output is:
There are 35 words that have at least one letter 'A' in them.
There were 35 words, that had one letter 'A' in them.
There were 3 words, that had two letters 'A' in them.
There were 0 words, that had three letters 'A' in them.
There were 0 words, that had 4 or more letters 'A' in them.
The entire number of letters is 416 and letter 'A' makes 9% out of them or 38 letters.
ok so i have two .txt files, one called "input.txt" and another called "output.txt". to create output i have to copy the text from input but replace all spaces between words with #'s and add a new line with the string "#NEW_LINE#" after each line of the original text
for example, if input.txt is this:
the unstoppable marching of time
that is slowly guiding us all towards
an inevitable death
then output.txt should be something like this:
the#unstoppable#marching#of#time
#NEW_LINE#
that#is#slowly#guiding#us#all#towards
#NEW_LINE#
an#inevitable#death
#NEW_LINE#
anyway you get the idea.
now i dont have a problem with this particular task, but then i am also asked to print on the screen a message that shows the total number of lines of text from both files, and another that prints the total number of #'s from output.txt. and while i dont have trouble with counting the lines, their numbers show up correctly but i do have trouble figuring out the #'s... ill explain.
here's part of the code i tried at first: [btw this whole thing takes place on one class, with no other methods apart from main, of course. i thought it would be simpler that way idk 💁♂️💅]
File fsrc=new File("input.txt");
File fdes=new File("output.txt");
int atCount = 0; //number of #'s
int lineCountIN=0; //number of input's lines
int lineCountOUT=0; //number of output's lines
FileReader fr = new FileReader(fsrc);
BufferedReader br =new BufferedReader(fr);
FileWriter fw = new FileWriter(fdes);
String s = null;
while((s=br.readLine())!=null)
{
if ((s.equals(" "))) {
fw.write(s.replace(" ","#"));
atCount++; }
else fw.write(s);
fw.write("\n");
lineCountOUT++;
lineCountIN++;
fw.write("#NEW_LINE#");
fw.write("\n");
lineCountOUT++;
fw.flush();
}
fw.close();
[...]
System.out.println("Total instances of # characters at output.txt: " + atCount);
the message that pops up on the screen will always be: "Total instances of # characters at output.txt: 0".
later i changed the if-else block to a do-while block:
do {
fw.write(s.replace(" ","#"));
atCount++; }
while ((s.equals(" ")));
but then the message does not return the exact number of #'s, in fact the number it shows just happens to be equal to lineCountIN for some reason (for example, for an input.txt file with 3 lines in total, the final message is: "Total instances of # characters at output.txt: 3")
so yeah thats pretty much it lmao i guess im using the atCount thingy wrong?? any help could be appreciated <3
Your approach finding the whitespace was not correct here is the solution, instead of searching in the whole string and count each line, you have to check each character and count it
public static void main(String[] args) {
String s = "the unstoppable marching of time\n" +
"that is slowly guiding us all towards\n" +
"an inevitable death";
int countSpace = 0;
if (s.contains(" ")) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
countSpace++;
}
}
s = s.replace(' ', '#');
}
System.out.println(s);
System.out.println(countSpace);
}
I was practicing problems in JAVA for the last few days and I got a problem like this:
I/p: I Am A Good Boy
O/p:
I A A G B
m o o
o y
d
This is my code.
System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c!=32)
{s1+=c;}
else
{
for(int j=0;j<s1.length();j++)
{System.out.println(s1.charAt(j));}
s1="";
}
}
The problem is I am not able to make this design.My output is coming as each character in each line.
First, you need to divide your string with space as a delimiter and store them in an array of strings, you can do this by writing your own code to divide a string into multiple strings, Or you can use an inbuilt function called split()
After you've 'split' your string into array of strings, just iterate through the array of strings as many times as your longest string appears, because that is the last line you want to print ( as understood from the output shared) i.e., d from the string Good, so iterate through the array of strings till you print the last most character in the largest/ longest string, and exit from there.
You need to handle any edge cases while iterating through the array of strings, like the strings that does not have any extra characters left to print, but needs to print spaces for the next string having characters to be in the order of the output.
Following is the piece of code that you may refer, but remember to try the above explained logic before reading further,
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IOException{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
// Split is a String function that uses regular function to split a string,
// apparently you can strings like a space given above, the regular expression
// for space is \\s or \\s+ for multiple spaces
int max = 0;
for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
int count = 0;
while(count<max){ // iterate till the longest string exhausts
for(int i=0;i<s.length;i++){
if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
else System.out.print(" "); // Two spaces otherwise
}
System.out.println();count++;
}
}
}
Edit: I am sharing the output below for the string This is a test Input
T i a t I
h s e n
i s p
s t u
t
I have a java program that reads a txt file and counts the words in that file. I setup my program so the String read from the txt file is saved as an ArrayList, and my variable word contains that ArrayList. The issue with my code is that my if statement does not seem to add a value to my count variable each time it detects space in the word string, it seems to only run the if statement once. How can I make it so the if statement finds a space, adds a +1 to my counter value, removes the space, and looks for the next space in the word variable's string? Here is the code:
import java.io.*;
import java.util.*;
public class FrequencyCounting
{
public static void main(String[] args) throws FileNotFoundException
{
// Read-in text from a file and store each word and its
// frequency (count) in a collection.
Scanner inputFile = new Scanner(new File("phrases.txt"));
String word= " ";
Integer count = 0;
List<String> ma = new ArrayList<String>();
while(
inputFile.hasNextLine()) {
word = word + inputFile.nextLine() + " ";
}
ma.add(word);
System.out.println(ma);
if(word.contains(" ")) {
ma.remove(" ");
count++;
System.out.println("does contain");
}
else {
System.out.println("does not contain");
}
System.out.println(count);
//System.out.println(ma);
inputFile.close();
// Output each word, followed by a tab character, followed by the
// number of times the word appeared in the file. The words should
// be in alphabetical order.
; // TODO: Your code goes here.
}
}
When I execute the program, I get a value of 1 for the variable count and I get a returned string representation of the txt file from my phrases.txt
phrases.txt is :
my watch fell in the water
time to go to sleep
my time to go visit
watch out for low flying objects
great view from the room
the world is a stage
the force is with you
you are not a jedi yet
an offer you cannot refuse
are you talking to me
Your if statement is not inside any loop, so it will only execute once.
A better approach, which would save a shit ton of runtime, is to read each line like you already do, use the String.split() method to split it on spaces, then add each element of the returned String[] to your list by using the ArrayList.addAll() method (if that one exist, otherwise (optionally, ensure the capacity and) add the elements one by one).
Then count by using the ArrayList.size() method to get the number of elements.
Based on the comments in your code :
// Read-in text from a file and store each word and its
// frequency (count) in a collection.
// Output each word, followed by a tab character, followed by the
// number of times the word appeared in the file. The words should
// be in alphabetical order.
My understanding is that you need to store count for every word, rather having a total count of words. For storing count for every word which should be stored itself in alphabetical order, it is better to go with a TreeMap.
public static void main(String[] args) {
Map<String, Integer> wordMap = new TreeMap<String, Integer>();
try {
Scanner inputFile = new Scanner(new File("phrases.txt"));
while(inputFile.hasNextLine()){
String line = inputFile.nextLine();
String[] words = line.split(" ");
for(int i=0; i<words.length; i++){
String word = words[i].trim();
if(word.length()==0){
continue;
}
int count = 0;
if(wordMap.containsKey(word)){
count = wordMap.get(word);
}
count++;
wordMap.put(word, count);
}
}
inputFile.close();
for(Entry<String,Integer> entry : wordMap.entrySet()){
System.out.println(entry.getKey()+"\t"+entry.getValue());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
What is your goal here ? Do you just want to read the file and count numbers of words?
You need to use a while loop instead of an if statement that'll just run once. Here's a better way to do what you want to do:
Scanner inputFile = new Scanner(new File("phrases.txt"));
StringBuilder sb = new StringBuilder();
String line;
int totalCount = 0;
while(inputFile.hasNextLine()) {
line = inputFile.nextLine();
sb.append(line).append("\n"); // This is more efficient than concatenating strings
int spacesOnLine = countSpacesOnLine(line);
totalCount += spacesOnLine;
// print line and spacesOnLine if you wish to here
}
// print text file
System.out.println(sb.toString());
// print total spaces in file
System.out.println("Total spaces" + totalCount);
inputFile.close();
Then add a method that counts the spaces on a line:
private int countSpacesOnLine(String line) {
int totalSpaces = 0;
for(int i = 0; i < line.length(); i++) {
if (line.charAt(i) == ' ')
totalSpaces += 1;
}
return totalSpaces;
}
You can achieve your objective with the following one liner too:
int words = Files.readAllLines(Paths.get("phrases.txt"), Charset.forName("UTF-8")).stream().mapToInt(string -> string.split(" ").length).sum();
probably I am late, but here is c# simple version:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace StackOverflowAnswers
{
class Program
{
static void Main(string[] args)
{
string contents = File.ReadAllText(#"C:\temp\test.txt");
var arrayString = contents.Split(' ');
Console.WriteLine("Number of Words {0}", arrayString.Length);
Console.ReadLine();
}
}
}
Language: Java.
Aim:
Boolean Array gridA[] should become true on whatever index is read from input (i.e. if input is "init_start 2 4 5 init_end" then gridA[] indexes 2,4 and 5 should become true). That much I managed to get working but I have two problems:
input:
init_start int int int int int (...) int init_end
for example: init_start 2 6 12 init_end
Problems:
any integer from input that exceeds the value of (instance variable) int L (which determines the index-length of the array) should be ignored, to prevent integers from outside the domain of Array gridA[] from having influence.
Using if(scanner.nextInt != L){} didn't seem to work.
I also need this method, or the body of the method to start when input begins with "init_start" and stop when input ends with "init_end".
How do write code so that it can read both String and integers from the same input?
I meant to do this using
if(scanner.Next=="init_start") followed by
a = scanner.NextInt; which, as I suspected, didn't work.
Attempts at solving:
After googling I tried putting String initialInputStart in a Scanner:
localScanner(initialInputStart);
but I failed to get that working. Other information I found suggested I'd close and reopen the scanner but I need the information to be read from a single line of input so I doubt that will help.
code:
java.util.Arrays.fill(gridA,false);
java.util.Arrays.fill(gridB,false);
String initialInput;
String initialInputStart;
int a;
int i;//only for testing
i = 0;//only for testing
System.out.println("type integers"); //only for testing
while( scanner.hasNextInt() && i<5){ //I can't find a way to make loop stop without missing input so I'm using i temporarily
a = scanner.nextInt();
gridA[a] = true;
System.out.print(a);
System.out.print(gridA[a]+" ");
i++;
}//end while
I wrote a little program which pretty much does what you described as your aim; I read line by line and split each into tokens I further process. The tokens describe what the data means/what state we are in. The actual data is parsed in the default: case in the switch(token) block and branches in behaviour from state to state (which is merely visible here as we only have two states: "init" and "not init", beside the keywords):
public static void main(String[] args) {
int L = 13; // not sure if this is needed
boolean[] gridA = new boolean[L];
Reader source;
/**
* from file:
* source = new FileReader("grid.csv");
*/
/**
* from classpath resource:
* source = new InputStreamReader(MyClass.class.getResourceAsStream("grid.csv"));
*/
/**
* from string:
* source = new StringReader("init_start 2 6 12 init_end");
*/
/**
* from std-in:
* source = new InputStreamReader(System.in);
*/
try(BufferedReader stream = new BufferedReader(source)) {
boolean init = false;
// loop
input_loop:
while(true) {
// read next line
String line = stream.readLine();
if(line == null) {
// end of stream reached
break;
}
if(line.trim().isEmpty()) {
// ignore empty lines
continue;
}
String[] tokens = line.split(" ");
for (String token : tokens) {
switch (token) {
// evaluate keywords
case "init_start":
init = true;
break;
case "init_end":
init = false;
break;
// for input from console
case "exit":
break input_loop;
default:
// parse input, based on state (expand "init" to an enum for more states)
if(init) {
// read init input
int index = Integer.parseInt(token);
if(index >= 0 && index < gridA.length) {
gridA[index] = true;
} else {
throw new RuntimeException("illegal grid index: " + index);
}
} else {
// read undefined input
throw new RuntimeException("unrecognized token: " + token);
}
break;
}
}
}
} catch(IOException ex) {
throw new RuntimeException("an i/o exception has occurred", ex);
}
System.out.println(Arrays.toString(gridA));
}
" How do write code so that it can read both String and integers from the same input?"
do you want to have an Input like this: "123, foo"
if thats the case use:
String input = scanner.nextLine();
String[] parts = input.split(",");//" " to split it at an empty space
String part1 = parts[0]; // 123
int Number = Integer.parseInt(part1) // you could inline it, but i chose this version for better refference
String part2 = parts[1]; //foo
if your Input looks like this "123 or foo"
you have to read the input as String and check the String afterwards if its a Number:
String input = scanner.nextLine();
if (text.contains("[a-zA-Z]+") == false){ //looks if the input does NOT contain any characters
int nummber = Integer.parseInt(input);
} else{
String text = input;
}
afterward you can compare your text:
For the first mentioned case:
if("init_start".equals(parts[1])){ //*
yourMethod();
}
For the other case:
if("init_start".equals(text)){ //*
yourMethod();
}
*Also:
"I meant to do this using if(scanner.Next=="init_start")"
*Very important! To compare Objects, such as String use .equals(). "==" only works on primitive types
Edit: I've read your example. You could go with a combination of my solutions. split the string at space(" ") and check parts[x] if it is an integer. But i wouldnt recommend this method! Why dont you split your input in three parts: init_start would start your function. After that your method would expect an input of Integers like "int int int" after you inserted the Integers your function could automatically stop or wait for the input "init_stop". That seems to me more reasonable. If you want to go with the single line solution you can evaluate the number of your int's by get tingparts[].lenght()-2
use this implementation:
public static void main(String args[]){
try{
Scanner in = new Scanner(System.in);
System.out.println("Enter a line");
String dat = in.readLine();
System.out.println(dat);
}
catch(IOException e){
System.out.println("IO ERROR !!!");
System.exit(-1);
}
}