I am trying to get the last element from the end of each line of my ArrayList/array.
For example i have these records int my list: (don't mind the language, Greek names)
Nikos Pappas : 321/2012999, C,8.53
Marios Athanasiou : 321/2012001, A,6.89
Stavroula Markou : 321/2011001, D,7.00
Giannis Kallogirou : 321/2009005, ST, 6.89
Nikoletta Stefanou : 321/2010001, D, 7.25
Stathis Petrou : 321/2011002, E, 8.10
Kostas Tzovalis : 321/2007667, C, 5.00
Michalis Kotsis : 321/2009723, D, 7.12
Maria Katsanou : 321/2012002, C, 5.50
And I want to take: 8.53, 6.89,....,5.50 (marks of students)
This is what I've made so far (the file is the file which contains the above info)
public static void main(String[] args) {
BufferedReader br = null;
ArrayList <String> list = new ArrayList <> ();
try
{
br = new BufferedReader(new FileReader("C:/Users/Stefi/Desktop/java_ask3.txt"));
String str;
//System.out.print("mpika");
while((str = br.readLine()) != null)
{
list.add(str);
System.out.println(str);
}
}
catch(IOException e)
{
System.out.println("Κάτι πήγε στραβά! Προσπάθησε πάλι.");
}
finally
{
try
{
if (br != null)
{
br.close();
}
}
catch(IOException e2)
{
System.out.println("Δεν μπορεσα να κλείσω το αρχείο.");
}
}
int x = list.size();
String [] array = new String[x];
array = list.toArray(array);
for(int i=0; i<array.length; i++)
{
System.out.println(array[i]);
}
String [] f = new String[list.size()];
String vathmos;
for(int i=0; i<array.length; i++)
{
vathmos = list.get(i).replaceAll("\\D+", "");
f[i] = vathmos;
}
System.out.println("\n\n\n Float Print\n");
for(int i=0; i<array.length; i++)
{
System.out.println(f[i]);
}
}
this is an example of my output:
3212012999853
3212012001689
3212011001700
3212009005689
It takes all the numbers it finds. But I don't know how to take only the last float number.
I know it's totally wrong to work like this, and work like this because I'll never get the float i want.
I also tried to convert my list into array and take the last element but didn't work out.
You can try this
String s = line.replaceAll(".*(\\d+\\.\\d+)$", "$1");
Split the line by a comma then get the last element of the resulting array
String[] splitArr = line.split(",");
String lastNumber = splitArr[splitArr.length - 1];
But best solution would be to have a Student class as suggested in comments
If you store your records as Strings, you can use the substring method:
grade = Double.parseDouble(array[i].substring(array[i].length() - 3)); if you are sure the grade is always in x.xx form at the end of each String.
Also consider creating a class that would contain all the information about students in seperate fields, for example:
public class Student{
public String name;
public String surname;
public int age;
public double grade;
}
Of course this is just an example, you may hide implementation and provide methods you want as well. Then you could create any kind of collection of Student objects, so getting the specified value of any field for any student would be easy.
I can suggest couple String functions to add to your code. This is not tested code though -
Using String.split();
//This will hold all the numbers as String
List<String> masterList = new ArrayList<String>();
while((str = br.readLine()) != null)
{
String [] lineValues = String.split(",");
int countElements = lineValues.Length();
masterList.Add(lineValues[countElements - 1]);
}
Using lastIndexOf();
//This will hold all the numbers as String
List<String> masterList = new ArrayList<String>();
while((str = br.readLine()) != null)
{
int lastIndex = str.lastIndexOf(",");
masterList.Add(str.substring(lastIndex, str.length() - 1));
}
Once you have the masterList populated, you can loop through it and extract the float using
Float.valueOf(masterList.get(i));
Related
So I have a text file that looks like this
4
10 orange
20 grape
100 Pencil Cases
4 Card
The first line is the number of objects. The next lines are the price and the name of the object. I have to find the object with the lowest price and return only the name of the object. (So, in this case "Card")
I put the txt into an Arraylist and split it so I could only get the numbers. I am trying to put the numbers into a new integer array to compare them. And this is the code I've tried.
public class Assignment {
public static void main(String[] args) {
try {
BufferedReader rd = new BufferedReader(new FileReader("C:\\Users\\USER\\Documents\\input.txt"));
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = rd.readLine()) != null)
{
lines.add(line);
}
rd.close();
for (int i =0; i<lines.size(); i++) {
String[] items = lines.get(i).split(" ", 2);
for (String s: items) {
System.out.println(s);
}
int[] array2 = new int[items.length];
int k =0;
for (int n= 2; n< items.length; n=n+2) {
array2[k] = Integer.parseInt(items[n]);
for (Integer l: array2) {
System.out.println(l); }
}
}
}
catch (Exception e) {
System.out.println("Error");
}
}
}
I think something is wrong with the array2 part. Can someone give a hint on how I should fix this?? New to stackoverflow and Java so I'm sorry if there is a problem with my question(or my grammar too...)!
I am trying to put the numbers into a new integer array to compare them
Here's how you can do it.
int[] array2 = new int[lines.size() - 1];
int k = 0;
for (int i = 1; i < lines.size(); i++) { //Start at row 1
String[] items = lines.get(i).split(" ", 2);
array2[k++] = Integer.parseInt(items[0]); //The first element is the price
}
System.out.println(Arrays.toString(array2)); //[10, 20, 100, 4]
But, with this, you cannot get the name of the item with the maximum price. So, you need to store both the name and the price together which I'll leave it to you.
I am trying to find the common characters in two strings just by using the for loop. The below code is working fine, if I provide two completely different strings ex.one and two but if I provide two strings with same input ex.teen and teen it doesn't work as expected.
import java.util.Scanner;
public class CommonAlphabets {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)){
System.out.println("Enter String one ");
String stringOne = input.nextLine();
System.out.println("Enter String two ");
String StringTwo = input.nextLine();
StringBuffer sb = new StringBuffer();
for(int i=0;i<stringOne.length();i++){
for(int j=0;j<StringTwo.length();j++){
if(stringOne.charAt(i)== StringTwo.charAt(j)){
sb.append(stringOne.charAt(i));
}
}
}
System.out.println("Common characters are " +sb.toString());
}
}
}
Should I create another nested for loop to find duplicates in the StringBuffer or is there a better way to handle this scenario.
You do not need an inner for loop but use contains instead
String stringOne = "one";
String stringTwo = "one";
StringBuilder sb = new StringBuilder();
for(int i=0;i<stringOne.length() && i < stringTwo.length ();i++){
if(stringOne.contains(String.valueOf(stringTwo.charAt(i))) &&
!sb.toString().contains(String.valueOf(stringTwo.charAt(i)))){
// check already added
sb.append(stringTwo.charAt(i));
}
}
System.out.println (sb.toString());
edit
check to make sure char to be added does not already exist in StringBuilder -
Could use a Set instead
If using a Set
Set<Character> set = new HashSet<> ();
your logic could be simplified to
if(stringOne.contains(String.valueOf(stringTwo.charAt(i)))){
set.add(stringTwo.charAt(i));
}
You can use Set for it.
Set<Character> set = new HashSet<>();
for(int i = 0; i<stringOne.length(); i++) {
for(int j = 0; j < StringTwo.length(); j++) {
if(stringOne.charAt(i) == StringTwo.charAt(j)){
set.add(stringOne.charAt(i));
}
}
}
StringBuilder sb = new StringBuilder();
for (Character c : set) {
sb.append(c);
}
System.out.println("Common characters are " + sb);
well your approach is fine as the result is showing what you are expecting there fore that code is fine, but you need to stop the duplication , therefore you have to write the code for 'sb' variable so that it will remove duplicates or write code in loop so that it wont provide duplicate.
as your code is becoming complicated to read so i would prefer that you make a method to write code to remove duplicate it will go like
static void removeDuplicate(StringBuilder s){
for(int i=0,i<s.length-1,i++){
for(int j=i+1,j<s.length,j++){
if(s.charAt(i)==s.charAt(j)){
s.deleteCharAt(j);
}
}
}
call this method before printing
Another approach you could try is - combine the two input strings, iterate over the concatenated string and return the characters which exist in both the strings.
Using a Set will ensure you do not add characters which get repeated due to the concatenation of the strings.
Here's what I wrote -
import java.util.HashSet;
public class HelloWorld {
private static Character[] findCommonLetters(String combined, String w1, String w2) {
HashSet<Character> hash = new HashSet<>();
for(char c: combined.toCharArray()) {
if(w1.indexOf(c) != -1 && w2.indexOf(c) != -1) {
hash.add(c);
}
}
return hash.toArray(new Character[hash.size()]);
}
public static void main(String []args){
// System.out.println("Hello World");
String first = "flour";
String second = "four";
String combined = first.concat(second);
Character[] result = findCommonLetters(combined, first, second);
for(char c: result) {
System.out.print(c);
}
System.out.println();
}
}
Demo here.
This is the best way to do this because it's time complexity is n so that why this is the best you could do.
import java.util.Scanner;
public class CommonAlphabets
{
public static void main(String[] args)
{
try (Scanner input = new Scanner(System.in))
{
System.out.println("Enter String one ");
String stringOne = input.nextLine();
System.out.println("Enter String two ");
String StringTwo = input.nextLine();
StringBuffer sb = new StringBuffer();
/**
* Assuming char as index of array where A-Z is from index 0 to 25 and a-z is index 26-51
*/
int[] alphabetArray1 = new int[52];
for(int i = 0, len = stringOne.length(); i < len; i++)
alphabetArray1[stringOne.charAt(i) > 94 ? stringOne.charAt(i) - 71 : stringOne.charAt(i) - 65] = 1;
int[] alphabetArray2 = new int[52];
for(int i = 0, len = StringTwo.length(); i < len; i++)
alphabetArray2[StringTwo.charAt(i) > 94 ? StringTwo.charAt(i) - 71 : StringTwo.charAt(i) - 65] = 1;
// System.out.println(Arrays.toString(alphabetArray1));
// System.out.println(Arrays.toString(alphabetArray2));
for (int i = 0; i < 52; i++)
if (alphabetArray1[i] == 1 && alphabetArray2[i] == 1)
sb.append((char) (i < 26 ? i + 65 : i + 71));
System.out.println("Common characters are " + sb.toString());
}
}
}
My code is supposed to separate a given String and covert the chosen letters into # and separate and concatenate the words with the chosen letter. My problem is with one of the methods (allWordsWith) in my code, it won't allow me to return a String array. (p.s, the codes that run this one are irrelevant, I'm not supposed to edit those).
import java.util.Arrays;
import java.util.Scanner;
public class LipogramAnalyzer {
private String line;
public LipogramAnalyzer(String text){
line = text;
}
public String mark (char letter){
String replaceletters = line.replace(letter, '#');
return replaceletters;
}
public String[] allWordsWith (char letter){
String[] arr = line.split(" ");
for ( String ss : arr) {
String ary[] = {ss};
for(int i = 0; i < ary.length; i++){
int numindex = ss.indexOf(letter);
if (numindex != -1){
String result = ary[i];
return result;
}
}
}
}
}
"It won't allow me to return a String array"
Sure it will. You're attempting to return a String:
String result = ary[i];
return result;
Even though the return type is a string array:
public String[] allWordsWith (char letter){
You need to return an array, as allWordsWith implies you want multiple values.
But the bigger problem is that you are initializing the result array to a single element
String ary[] = {ss};
and thes lengths of arrays can't be changed after initialization. This means that ary.length in this loop
for(int i = 0; i < ary.length; i++){
will always equal one. That is not what you want.
In addition, you are searching the strings in the result array (ary), even though you just created it, meaning it has nothing in it--that is, all the values are null.
If you want a list of all the strings in line that have the letter in it, try
public String[] allWordsWith (char letter){
String[] asAllWordsInLine = line.split(" ");
java.util.ArrayList<String> alsAllWordsWithChar = new java.util.ArrayList<String>();
for ( String ss : asAllWordsInLine) {
if(ss.indexOf(letter) != -1) {
alsAllWordsWithChar.add(ss);
continue; //No need to check any more letters.
}
}
return alsAllWordsWithChar.toArray(new String[alsAllWordsWithChar.size()]);
}
I've changed the array to a list, since you can't know how many strings will have letter in it. A list can change size, an array can't. When no strings match, this returns an empty array, which is preferred over null. (more info)
I've also made the variable names more meaningful, and stopped checking a word after it matches a character (with continue, which short-circuits the current for-loop iteration).
Finally, the function is not returning anything until all strings have been analyzed, meaning after the for-loop completes. In your original code the return is inside the loop, meaning only the first string is returned.
A useful testing function:
public static final void main(String[] igno_red) {
testLine('b', "abc def ghi cba def ghi");
}
private static final void testLine(char c_letter, String s_line) {
System.out.println("Line: \"" + s_line + "\"");
String[] asAllWordsWith = (new LipogramAnalyzer(s_line)).allWordsWith(c_letter);
System.out.println("Words with '" + c_letter + "': " + Arrays.toString(asAllWordsWith));
}
Return the ary not ary[i]
for(int i = 0; i < ary.length; i++){
int numindex = ss.indexOf(letter);
if (numindex != -1){
String result = ary[i];
/*here*/ return ary;
}
You can return an array. Try return ary instead of return ary[i].
Also, your function must return something in all cases. In other words, you have to have a return statement after your for loops.
public String[] allWordsWith (char letter){
String[] arr = line.split(" ");
for ( String ss : arr) {
String ary[] = {ss};
for(int i = 0; i < ary.length; i++){
int numindex = ss.indexOf(letter);
if (numindex != -1){
String result = ary[i];
// or here return ary;
}
}
}
return ary;
}
Return the array
You are trying to return a String instead of String[] (String array)
Change the code:
if (numindex != -1) {
String result = ary[i];
return result;
}
To:
if (numindex != -1) {
return new String[]{ary[i]};
}
// afrer first for loop
return arr;
If you want to return a complete String-Array at once, I have modified your function (not tested):
public String[] allWordsWith (char letter){
String[] arr = line.split(" ");
String[] result = new String[ary.length];
for ( String ss : arr) {
String ary[] = {ss};
for(int i = 0; i < ary.length; i++){
int numindex = ss.indexOf(letter);
if (numindex != -1){
result[i] = ary[i];
}
}
}
return result;
}
As already said, you're returning a String instead of a String[]. Also note that your code will only ever return a single "word". I modified your code to add every word that contains your character and add it to a List. At the end of the loop the List is converted to a String[].
public String[] allWordsWith(char letter)
{
String[] arr = line.split(" ");
List<String> result = new ArrayList<>();
for (String ss : arr) {
int numindex = ss.indexOf(letter);
if (numindex != -1) {
result.add(ss);
}
}
return result.toArray(new String[result.size()]);
}
I have a problem in my project math.
My project is to write a program that reads a set of elements and its relations. Your input data will be from a text file. (SetRelation).
{1,2,3} {(1,1),(2,2),(3,3),(1,2),(1,3),(2,3)}
I have no problem reading the text file into the program but I'm stuck when I want to try to put the relation into the two dimensional array.
For example: {(1,1),(2,2),(3,3),(1,2),(1,3),(2,3)}
The two dimensional array would have to be like this:
col[0][1][2]
[0] 1 1 1
[1] 1 1
[2] 1
I don't know how to set one into two dimensional array because there are various relations in the text file.
This is my coding.
import javax.swing.*;
import java.util.ArrayList;
import java.io.*;
import java.util.StringTokenizer;
import java.lang.*;
import java.util.*;
public class tests
{
public static int s1[][];
public static int s2[][];
public static int s3[][];
public static int s4[][];
public static int s5[][];
public static int s6[][];
public static int s7[][];
public static int s8[][];
public static int s9[][];
public static int s10[][];
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader infile = null;
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
ArrayList arr3 = new ArrayList();
ArrayList arr4 = new ArrayList();
try
{
infile = new BufferedReader (new FileReader ("numbers.txt"));
String indata = null;
while ((indata = infile.readLine())!= null)
{
StringTokenizer st = new StringTokenizer(indata," ");
String set = st.nextToken();
arr1.add(set);
String relation = st.nextToken();
arr2.add(relation);
}
for(int i =0; i < arr2.size(); i++)
{
String r = arr2.get(i).toString();
String result = r.replaceAll("[{}(),; ]", "");
arr3.add(result);
}
for(int i = 0; i < arr3.size(); i++)
{
System.out.println(arr3.get(i).toString());
}
for(int i =0; i < arr1.size(); i++)
{
String s = arr1.get(i).toString();
String result = s.replaceAll("[{}(),; ]", "");
arr4.add(result);
}
int set1 = Integer.parseInt(arr4.get(0).toString());
String ss1 = arr4.get(0).toString();
int a = ss1.length();
s1 = new int[a][a];
int sA[][];
/*for(int row=1;row< a;row++)
{
for(int col=0;col < a;col++)
{
sA = new int[row][col];
int firstNo = Integer.parseInt(arr3.get(row).toString());
int secondNo = Integer.parseInt(arr3.get(col).toString());
sA = new int [firstNo][ secondNo] ;
System.out.print(sA);
}
System.out.println();
}*/
char arrA;
char indOdd=' ',indEven=' ';
char[] cArr = arr3.get(0).toString().toCharArray();
//System.out.println(arr3.get(0).toString().length());
int l = arr3.get(0).toString().length();
int arr10[][] = new int[(l/2)][2];
for(int i=0;i< 2;i++)
{
for(int row = 0; row < (l/2);row++)
{
for(int gh = 0;gh < l;gh++)
{
if(i%2==0)
{
indEven = cArr[gh];
System.out.println(indEven);
arr10[row][i] = indEven;
//System.out.println(arr10[row][i]);
//row++;
}
else
{
indOdd = cArr[gh+1];
System.out.println(indOdd);
arr10[row][i] = indOdd;
//row++;
}
}
}
//arr10 = new int[indOdd][indEven];
//System.out.println(arr10);
}
}
catch (FileNotFoundException fnfe)
{
System.out.println("File not found");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
infile.close();
}
}
But I'm stuck how to set one into the two dimensional array if the relation is {(a,b),(a,c),(b,a),(b,c),(c,c)}; and {(33,33),(45,45),(67,67),(77,77),(78,78)};
So, you have two problems: parsing the input and setting the array.
To parse the input, think about the format you're given. An opening curly brace, a bunch of ordered pairs, then a closing brace. Think about this pseudocode:
Read in a left curly brace
While the next character is not a right curly brace{
Read in a left parenthesis
Get the first number and put it in a variable!
Read in a comma
Get the second number and put it in a variable!
Read in a right parenthesis
Store your relation in the array!
}
Now your issue is just how to put it in the array. Your relations are practically already indexes into the grid! Note the 0-indexing, so just subtract 1 from both, and set the resulting coordinate equal to 1.
array[first number-1][second number-1]=1;
Just a TIP:
If your set is for example {b,c,e} and want to have somewhere stored relation elemnt <-> index like b<==>0, c<==>1, e<==>2 you can store that elements in List and then use method indexOf().
I mean something like this
List<String> list=new ArrayList<String>();
list.add("b");
list.add("c");
list.add("e");
System.out.println(list.indexOf("c"));//return 1
System.out.println(list.indexOf("e"));//return 2
System.out.println(list.indexOf("b"));//return 0
Now you just have to figure out how to use it to create your array.
i am here with another problem in my code since i am new to java. my task is to read a text file that contains some 300 records and record has 13 fields . i am trying to calculate the sum of each field for example, if age is my first field them sum of the age of all 300 people and then store it in an array index.
import java.io.*;
import java.util.Vector;
public class Mean
{
private static Vector contents;
private static BufferedReader br;
private static FileInputStream inputstream;
private static FileOutputStream outputstream;
public Mean()
{
contents = new Vector();
}
public void doDuplicationRemoval(String filename)
{
try{
inputstream = new FileInputStream(filename);
br = new BufferedReader(new InputStreamReader(inputstream));
String string = "";
while((string = br.readLine())!= null)
{
String[] split = string.split(",");
Vector vector = new Vector();
for(int i=0; i<split.length; i++)
vector.add(split[i].trim());
if(!vector.contains("?"))
{
contents.add(split);
}
}
}
catch(Exception err){
System.out.println(err);
}
}
public void doDataConv(String filename)
{
DataConversion.readFile(contents);
DataConversion.writeFile(filename);
}
public static void doDataConversion(Vector contents)
{
DataConversion.readFile(contents);
for(int i=0; i<contents.size(); i++)
{
String string = "";
String[] split = (String[])contents.get(i);
split[0] += getAge(split[0]);
System.out.println(split[0]);
}
}
private static String getAge(String src)
{
String age = src;
return age;
}
public static void main(String [] args) {
Mean dr;
dr = new Mean();
dr.doDuplicationRemoval("input.txt");
dr.doDataConv("inp_out.txt");
dr.doDataConversion(contents);
}
}
the input is
63
67
50
my aim is to get output as 180
but am getting
6363
6767
5050
can someone help me to fix the problem.
This looks like the first problem to me:
private static String getAge(String src)
{
String age = src;
return age;
}
You're treating the age as a string. If you want to treat it as a number, you should be parsing it (e.g. with Integer.parseInt).
Here's the second problem:
String string = "";
String[] split = (String[])contents.get(i);
split[0] += getAge(split[0]);
System.out.println(split[0]);
That's only ever changing the value of split[0], which is then overwritten when you reassign it in the next iteration. You need something like:
int sum = 0;
for(int i=0; i<contents.size(); i++)
{
String[] split = (String[])contents.get(i);
sum += getAge(split[0]); // After changing getAge to return an int
}
System.out.println(sum);
Your not adding numbers but concatenating Strings:
split[0] += getAge(split[0]);
To sum up the values (e.g. the numeric content of your first column fields)
Define a local variable, like int sum = 0; outside the loop
parse the values from the Strings (Integer.parseInt(split[0])) and
add every parsed value to sum.
The problem is you line
split[0] += getAge(split[0]);
As the type of your split table is String, it will concatenate the values. You need a result table, like:
int[] result = new int[];
And then:
result[0] += getAge(split[0]);
I will try to formulate a good design for your purpose:
Create a class with the structure of a record. Let's name it Record
Instanciate a Record object with each line you read
Put in a Record table
You can create another Record with all the sums
Don't use Vector. If you need a list, use ArrayList (except in a multithreaded context). Vector is just a legacy class from before Java 2. It's obsolete.
your actual error is here as you are using + to add two string which contains integer
split[0] += getAge(split[0]);//here split[0] is String 63, getAge(split[0])
//retuns also String 63 hence addition gives "63" + "63" = "6363"
doing string addition that is concatenation
Integer.parseInt()
so make conversion as follow:
split[0] = new Integer (Integer.parseInt(split[0]) +
Integer.parseInt( getAge(split[0]))).toString()
if you want to store values in integer array then make another array of integer to store values.
if you want to store result in int array then do as follow:
int agesum[] = new int[]
agesum[0] += Integer.parseInt( getAge(split[0]));