I wanted to store name values in String a[] = new String[3];
public static void main(String[] args) throws IOException {
BufferedReader bo = new BufferedReader(new InputStreamReader(System.in));
String name = bo.readLine();
String a[] = new String[3];
}
}
I guess this should suffice:
String a[] = new String[3];
for(int i=0; i<a.length;i++) {
String name = bo.readLine();
a[i] = name;
}
If your name represents names separated by space, try this:
String a[] = name.split(" ");
If you're working from the console I think this is the easiest way for a beginner to tackle user input:
import java.util.Scanner;
public class ReadToStringArray {
private static String[] stringArray = new String[3];
// method that reads user input into the String array
private static void readToArray() {
Scanner scanIn = new Scanner(System.in);
// read from the console 3 times
for (int i = 0; i < stringArray.length; i++) {
System.out.print("Enter a string to put at position " + i + " of the array: ");
stringArray[i] = scanIn.nextLine();
}
scanIn.close();
System.out.println();
}
public static void main(String[] args) {
readToArray();
// print out the stringArray contents
for (int i = 0; i < stringArray.length; i++) {
System.out.println("String at position " + i + " of the array: " + stringArray[i]);
}
}
}
This method uses the java's native Scanner class. You can just copy and paste this and it will work.
Related
I am given a text file as follows:
0:1,2,3
1:3
2:
3:2
I'm trying to read in from the file then add it to a singly linked list array. Here is what I have so far. I'm able to print out the first part of the file however struggling to print out the values following the ":".
Here is my code.
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> arrayList = new ArrayList<>();
Scanner sc = new Scanner(new File(args[0]));
while (sc.hasNextLine()) {
arrayList.add(sc.nextLine());
}
SinglyLinkedList singlyLinkedList[] = new SinglyLinkedList[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
String dag = arrayList.get(i);
String[] daglist = dag.split(":");
int listindex = Integer.parseInt(daglist[0]);
System.out.println(listindex + ":");
Thanks in advance
Here is the following code that I've tried.
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> arrayList = new ArrayList<>();
Scanner sc = new Scanner(new File(args[0]));
while (sc.hasNextLine()) {
arrayList.add(sc.nextLine());
}
SinglyLinkedList singlyLinkedList[] = new SinglyLinkedList[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
String dag = arrayList.get(i);
String[] daglist = dag.split(":");
int listindex = Integer.parseInt(daglist[0]);
System.out.println(listindex + ":");
// for (int j = 0; j < arrayList.size(); j++) {
// String[] daglist1 = dag.split(",");
// int listvalues = Integer.parseInt(daglist1[1]);
// System.out.println(listindex + ":" + listvalues + " ");
// }
}
}
This is giving me an infinite loop and not printing out correctly.
Suppose this is my .txt file ABCDBCD and I want to use .substring to get this:
ABC BCD CDB DBC BCD
How can I achieve this? I also need to stop the program if a line is shorter than 3 characters.
static void lesFil(String fil, subsekvens allHashMapSubsequences) throws FileNotFoundException{
Scanner scanner = new Scanner(new File("File1.txt"));
String currentLine, subString;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
for (int i = 0; i + subSize <= currentLine.length(); i++){
subString = currentLinje.substring(i, i + subSize);
subSekStr.putIfAbsent(subString, new subsequence(subString));
}
}
scanner.close();
With a minor changes of your code:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("C:\\Users\\Public\\File1.txt"));
String currentLine, subString;
int subSize = 3;
while (scanner.hasNextLine()) {
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
if (currentLine.length() < subSize) {
break;
}
for (int i = 0; i + subSize <= currentLine.length(); i++) {
subString = currentLine.substring(i, i + subSize);
System.out.print(subString + " ");
}
System.out.print("\n");
}
scanner.close();
}
This may be what you need
String str = "ABCDBCD";
int substringSize = 3;
String substring;
for(int i=0; i<str.length()-substringSize+1; i++){
substring = str.substring(i, i+substringSize);
System.out.println(substring);
}
import java.util.*;
public class Main
{
public static void main(String[] args) {
String input = "ABCDBCD";
for(int i = 0 ; i < input.length() ; i++) {
if(i < input.length() - 2) {
String temp = input.substring(i,i+3);
System.out.println(temp);
}
}
}
}
I read the information in a .txt file and now I would like to store the lines of information from the text into a String Array or a variable.
The information in the .txt file is as given:
Onesimus, Andrea
BAYV
Twendi, Meghan
RHHS
Threesten, Heidi
MDHS
I want to store BAYV, RHHS, MDHS into a different array from the names.
import java.io.File;
import java.util.Scanner;
class testing2 {
public static void main(String [] args) throws Exception {
File Bayviewcamp = new File ("H:\\Profile\\Desktop\\ICS3U\\Bayviewland Camp\\Studentinfo.txt");
Scanner scanner = new Scanner (Bayviewcamp);
while (scanner.hasNextLine())
System.out.println(scanner.nextLine());
Check whether names matches with the regex "[A-Z]+"
List<String> upperCaseList = new ArrayList<>();
List<String> lowerCaseList = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] names = scanner.nextLine().split(",");
for(String name:names) {
if(name.matches("[A-Z]+")) {
upperCaseList.add(name);
}
else {
lowerCaseList.add(name);
}
}
}
As per your example, some of the names has leading spaces. you may have to trim those spaces before you compare with the regex
for(String name:names) {
if(name.trim().matches("[A-Z]+")) {
upperCaseList.add(name.trim());
}
else {
lowerCaseList.add(name.trim());
}
}
Below code has few restrictions like:
There must be format that you said (name and next line value)
Array size is 100 by default but you can change as you want
By name I mean one line: (Onesimus, Andrea) it's under first index in names array.
private static final int ARRAY_LENGTH = 100;
public static void main(String[] args) throws FileNotFoundException {
boolean isValue = false;
File txt = new File("file.txt");
Scanner scanner = new Scanner(txt);
String[] names = new String[ARRAY_LENGTH];
String[] values = new String[ARRAY_LENGTH];
int lineNumber = 0;
while (scanner.hasNextLine()) {
if (isValue) {
values[lineNumber / 2] = scanner.nextLine();
} else {
names[lineNumber / 2] = scanner.nextLine();
}
isValue = !isValue;
lineNumber++;
}
for (int i = 0; i < ARRAY_LENGTH; i++) {
System.out.println(names[i]);
System.out.println(values[i]);
}
}
Below code return separated names:
private static final int ARRAY_LENGTH = 100;
public static void main(String[] args) throws FileNotFoundException {
boolean isValue = false;
File txt = new File("file.txt");
Scanner scanner = new Scanner(txt);
String[] names = new String[ARRAY_LENGTH];
String[] values = new String[ARRAY_LENGTH];
int namesNumber = 0;
int valuesNumber = 0;
while (scanner.hasNextLine()) {
if (!isValue) {
String tempArrayNames[] = scanner.nextLine().split(",");
values[valuesNumber++] = tempArrayNames[0].trim();
values[valuesNumber++] = tempArrayNames[1].trim();
} else {
names[namesNumber++] = scanner.nextLine();
}
isValue = !isValue;
}
}
I have a problem. I need to use the first row of the txt as my string and then look in the same txt the occurrences and print the number, but I have a problem, for example; if my txt is like: wordwordword and my string is word, it only counts the first word, it does´t print the counter: 3, print the counter: 1. How can I solve this?
Demo.java
import java.io.*;
import java.util.*;
public class Demo {
public static void main(String args[]) throws java.io.IOException {
BufferedReader in = new BufferedReader(new FileReader("c.txt"));
Scanner sc = new Scanner(System.in);
String s1;
s1 = in.readLine();
String Word;
Word = s1;
String line = in.readLine();
int count = 0;
String s[];
do {
s = line.split(" ");
for (int i = 0; i < s.length; i++) {
String a = s[i];
if (a.contains(Word))
count++;
}
line = in.readLine();
} while (line != null);
System.out.println("first line: " + s1);
System.out.print("There are " + count + " occurences of " + Word
+ " in ");
java.io.File file = new java.io.File("c.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
String word = input.nextLine();
System.out.print(word);
}
}
}
txt:
GAGCATAGA
CGAGAGCATATAGGAGCATATCTTGAGCATACCGAGCATATGAGCATAATATACCCGTCCGAGAGCATACACTGAGCATAAAGGAGCATAGAGCATACAACTGAGAATGGAGCATAGAGCATACGGAGCATAAGAGCATAGAGCATAGAGCATACGGAGCATAGAGCATAGAGCATAGCCGATGGGGAGCATACTGTTACGTAGAGCATACGAGCATAGCGCAAGAGCATAAAGAGCATAGAGCATATGAGCATATAGAGCATACGAGCATACAAGATCCGGGGAGCATAGCGAGGTAATAGTCGGAGCATAGAGCATAGAGCATATGAGCATACGGGAGCATAAATGAGCATAAGGAGCATAGAGCATAGAGCATAAGAGCATATCTCGAGCATAAGCGAGCATAGAGCATAAAAATCAATCACGTTGAGCATATGAGCATAAATACTGGAGCATAGATCGAGCATAGTAGAGCATACGAGCATAGAGCATAGGAGCATAAGAGCATATGAGCATATTGAGCATATGAAGGAGCATAAAAATGAGCATAAGGAGCATACCATCGTTGAGCATAATCCGAGCATAGGAGCATAGAATAGAGCATAGACAGGAGTTTTTGGAGCATATGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATATTCGAGCATAATTGAGCATATGAGCATAGAGCATATGGAGCATAGGCTGAGCATACCGAGCATAGCAATTAGAGCATAATCCTAGGGAGCATAGGAGCATACGTGAGCATAGCTGAGCATAGAGCATAGAGCATAGTGTTCGAGCATAGAGCATAGAGCATATGAGCATAGAGCATACTTGAGCATATGGTACGAGCATAGGAGCATATAAGGAGGAGCATATCGAGCATAGAGCATAGGCCTGGCCAGAGCATATAACCGAGCATAGGGTTGGAGCATAAGGCCGGAGCATACGAGCATACGAGCATATGAAATGAGCATAATGTGAGCATAGAGCATATCGAGCATATGAGCATAGGAGCATA
in this example with the txt, the program should print the counter= 21
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Match {
public static String TEXT_FILE_LOCATION="input.txt";
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File(TEXT_FILE_LOCATION));
String stringToSearch=in.nextLine();
StringBuffer buffer=new StringBuffer();
for(;in.hasNext();){
buffer.append(in.next());
}
Pattern pattern = Pattern.compile(stringToSearch);
Matcher matcher = pattern.matcher(buffer.toString());
int from = 0;
int count = 0;
while(matcher.find(from)) {
count++;
from = matcher.start() + 1;
}
System.out.println("Number of matches : "+count);
}
}
You can do it by looping through your text then match the string with part of the text.
Here it is:
public static void main(String[] args) {
String word = "word";
String text = "wordwordword";
int count = 0;
for(int i =0 ; i <text.length() ; i++){
for(int j = 0 ; j < word.length();j++){
if((j+i)>=text.length())break;
if(word.charAt(j)!=text.charAt(j+i))break;
if(j==word.length()-1)count++;
}
}
System.out.println(count);//prints 3
}
Also you could use .toCharArray() to get the characters in the string before looping to enhance the performance.
Here is the modified code for that :
public static void main(String[] args) {
char[] word = "word".toCharArray();
char[] text = "wordwordword".toCharArray();
int count = 0;
for(int i =0 ; i <text.length ; i++){
for(int j = 0 ; j < word.length;j++){
if((j+i)>=text.length)break;
if(word[j]!=text[j+i])break;
if(j==word.length-1)count++;
}
}
System.out.println(count);
}
I've been having some difficulties reading in information from a file into separate arrays. An example of the information in the file is:
14 Barack Obama:United States
17 David Cameron:United Kingdom
27 Vladimir Putin:Russian Federation
19 Angela Merkel:Germany
While I can separate the integers into an array, I am having trouble creating an array for the names and an array for the countries. This is my code thus far:
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
Scanner input = new Scanner(new File("names.txt"));
size = input.nextInt();
int[] rank = new int[size];
for (int i = 0; i < rank.length; i++) {
rank[i] = input.nextInt();
input.nextLine();
}
String[] name = new String[size];
for (int i = 0; i <name.length; i++) {
artist[i] =
I think that I would have to read in the line as a string and use indexOf to find the colon in order to start a new array but I'm unsure as to how to execute that.
I just tried to solve your problem in my ways. It was just for a time pass. Hopes this may helps you.
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
File file = new File("names.txt");
FileReader fr = new FileReader(file);
String s;
LineNumberReader lnr = new LineNumberReader(new FileReader(file));
lnr.skip(Long.MAX_VALUE);
size = lnr.getLineNumber()+1;
lnr.close();
int[] rank = new int[size];
String[] name = new String[size];
String[] country = new String[size];
try {
BufferedReader br = new BufferedReader(fr);
int i=0;
while ((s = br.readLine()) != null) {
String temp = s;
if(temp.contains(":")){
String[] splitres = temp.split(":");
String sub = splitres[0];
rank[i] = Integer.parseInt(sub.substring(0,sub.indexOf(" "))); // Adding rank to array rank[]
name[i] = sub.substring(sub.indexOf(" "), sub.length()-1); // Adding name to array name[]
country[i] = splitres[1]; // Adding the conutries to array country[]
}
i++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This is a bit more efficient because it goes through the file only once.
public static void main(String[] args) throws FileNotFoundException {
// create an array list because the size of the array is still not know
ArrayList<Integer> ranks = new ArrayList<Integer>();
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> countries = new ArrayList<String>();
// read the input file
Scanner input = new Scanner(new File("names.txt"));
// read each line
while (input.hasNext()) {
String wholeLine = input.nextLine();
// get the index of the first space
int spaceIndex = wholeLine.indexOf(" ");
// parse the rank
int rank;
try {
rank = Integer.parseInt(wholeLine.substring(0, spaceIndex));
} catch (NumberFormatException e) {
rank = -1;
}
// parse the name & country
String[] tokens = wholeLine.substring(spaceIndex + 1).split(":");
String name = tokens[0];
String country = tokens[1];
// add to the arrays
ranks.add(rank);
names.add(name);
countries.add(country);
}
// get your name and country arrays if needed
String[] nameArr = names.toArray(new String[]{});
String[] countryArr = countries.toArray(new String[]{});
// the rank array has to be created manually
int[] rankArr = new int[ranks.size()];
for (int i = 0; i < ranks.size(); i++) {
rankArr[i] = ranks.get(i).intValue();
}
}