Splitting an integer into an array - arrays

I am trying to take an array of information (array of 8) and split it so that I can send it to an ArrayList.
I can run a a split if I create and make them all strings, but I am trying to reduce the coding (as there has to be a better way).
The first 4 of the array are strings, and the next 4 are int.
ArrayList<student> studentID = new ArrayList<student>();
String[] studentInfo = {"","","",""};
int [] studentInfo2 = {0,0,0,0};
for (int x = 0; x < students.length; x++)
{
if (x < 4)
{
studentInfo = students[x].split(",");
}
else
{
**studentInfo2 = students[x]();**
}
for (int counter = 0; counter < 8; counter++)
{
if (counter < 4) //First 4 in the array are strings
{
studentID.add(new student(studentInfo[counter]));
}
else //Everything after the first 4 are Integers
{
studentID.add(new student(Integer.valueOf(studentInfo[counter])));
}
}
}
I cannot figure out how to split the last 4 into an array, as I did the first 4.
EDIT:
static String[] students = "1,John,Smith,John2233#gmail.com,20,88,79,59,
2, Becky,Jones,JonesBecky123#hotmail.com,44,90,89,44,99"
This information is being piped into a class as seen below:
public class student
{
private String studentNumber;
private String firstName;
private String lastName;
private String emailAddress;
private int age;
private int []score = {0,0,0};
private int score0;
private int score1;
private int score2;
/**
* Constructor for objects of class studentObject
*/
public student(String theStudentNumber, String theFirstName, String theLastName, String theEmailAddress, int theAge, int theScore0, int theScore1, int theScore2)
{
// initializing the instance variables
studentNumber = theStudentNumber;
firstName = theFirstName;
lastName = theLastName;
emailAddress = theEmailAddress;
age = theAge;
score[0] = theScore0;
score[1] = theScore1;
score[2] = theScore2;
}
Then it will call this method
public void print(student printStudentInfo)
{
System.out.print(printStudentInfo.getStudentNumber()+"\t");
System.out.print("First Name: " + printStudentInfo.getStudentNumber()+"\t");
System.out.print("Last Name: " + printStudentInfo.getStudentNumber()+"\t");
System.out.print("Age: " + printStudentInfo.getStudentNumber()+"\t");
System.out.print("Scores : " + printStudentInfo.getStudentNumber()+"\t");
System.out.println();
}
Thanks for the help ahead of time.

Related

How to figure out a set of arrays to add a ranking system for student gpa from a text file

public static void main(String[] args) throws FileNotFoundException
{
File file = new File("studentdata.txt");
try (Scanner scan = new Scanner(file))
{
String[] IDs = new String[1000];
double[] GPAs = new double[1000];
int counter;
counter = 0;
String STUDENTID;
double GPA;
int NUMofSTUD = 0;
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
while (scan.hasNext())
{
STUDENTID = scan.next();
NUMofSTUD ++;
GPA = scan.nextDouble();
IDs[counter] = STUDENTID;
GPAs[counter] = GPA;
List<GpaCount> GpaCounts = new ArrayList<>();
{
int[] index = new int[GPAs.length];
for (int i = 0; i < GPAs.length; i++)
{
int count = 0;
for (int j = 0; j < GPAs.length; j++)
{
if (GPAs[j] > GPAs[i])
{
count++;
}
}
index[i] = count + 1;
Comparator<GpaCount> comparator = (GpaCount o1, GpaCount o2) -> Integer.compare(o1.getCount(), o2.getCount());
Collections.sort(GpaCounts, comparator);
}
}
if (GPA >= 3.5)
{
one ++;
}
if (GPA >= 3.0 && GPA < 3.5)
{
two++;
}
if (GPA >= 2.5 && GPA < 3.0)
{
three++;
}
if (GPA >= 2.0 && GPA < 2.5)
{
four++;
}
if (GPA >= 1.5 && GPA < 2.0)
{
five++;
}
if (GPA >= 1.0 && GPA < 1.5)
{
six++;
}
if (GPA >= .5 && GPA < 1.0)
{
seven++;
}
if (GPA < .5)
{
eight ++;
}
System.out.println("Student ID: " + STUDENTID +
" GPA: " + GPA + " Rank: " + GpaCounts);
}
System.out.println("Histogram of GPA");
System.out.println("GPA 0.0 to 0.4: "+ eight + " students "
+ Stars(eight/10));
System.out.println("GPA 0.5 to 0.9: "+ seven + " students "
+ Stars(seven/10));
System.out.println("GPA 1.0 to 1.5: "+ six + " students "
+ Stars(six/10));
System.out.println("GPA 1.5 to 1.9: "+ five + " students "
+ Stars(five/10));
System.out.println("GPA 2.0 to 2.4: "+ four + " students "
+ Stars(four/10));
System.out.println("GPA 2.5 to 2.9: "+ three + " students "
+ Stars(three/10));
System.out.println("GPA 3.0 to 3.4: "+ two + " students "
+ Stars(two/10));
System.out.println("GPA 3.5 to 4.0: "+ one + " students "
+ Stars(one/10));
System.out.println(NUMofSTUD);
}
}
/* nt[] getRanksArray(double[] array)
{
int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] > array[i]) {
count++;
}
}
result[i] = count + 1;
}
return result;
} */
public static String Stars(int number)
{
StringBuilder temp = new StringBuilder();
for(int i=0; i<number; i++){
temp.append("*");
}
return temp.toString();
}
}
I am stuck at the ListGpa, it shows the variable is never read. This a a Java program that takes a text document with student ID and GPA(theoretical). It outputs everything correctly, other than the fact it won't add the rank to the ends of the names.
For both of your questions:
ListGPA is declared but never used and it's simply a warning
suggesting you to remove it it from your code. I looked over your
code and didn't see it being used anywhere after it was declared.
Your rank "*" method is correct, however when you invoke the method
like Stars(one/10) and let's say one is equal to 5, then it's stars(5/10) =
stars(0) because your method parameter is an int and the decimal value is
truncated. I created my own text-file with 10 students at 4.0 GPA each and a
star did print.
My suggestion is to break your program into helper methods to perform each task. For example, I would create a method to read and extract data from your input file and return a list of Students. Then I would create another method that takes the list of Students and perform the next step. The idea is to separate the logic and maintain readability. Your program has issues in it and having all of that logic in one place is extremely messy. I would suggest that you go back and store your input in a list of student objects and work your way from there.
class Student {
/* Ideally you would make these private and create getters/setters */
public int id;
public double gpa;
public Student(int id, double gpa) {
this.id = id;
this.gpa = gpa;
}
/* Overriding toString() and equals() methods is something to think about */
}
public class Demo {
public static void main(String[] args) {
List<Student> students = generateStudentList(new File("studentdata.txt"));
printStudentList(students); // Should output data of all students
}
public static List<Student> generateStudentList(File file) {
List<Student> students = new ArrayList<>();
try (Scanner scanner = new Scanner(file)) {
while(scanner.hasNext()) {
int id = scanner.nextInt();
double gpa = scanner.nextDouble();
students.add(new Student(id, gpa));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return students;
}
public static void printStudentList(List<Student> students) {
System.out.println("Number of students: " + students.size());
for(Student student : students) {
int id = student.id;
double gpa = student.gpa;
System.out.println("Student ID: " + id + "\t" + "GPA: " + gpa);
}
}
}
See how I separated my logic into methods. You can complete this problem by
thinking about what you need to do first. Use your results to solve the next task. It's all a systematic process in order to solve the problem as a whole.
If you have any questions feel free to ask. Best of luck!

Permutation of a string so that the patterns match

The question is to count how many permutations of a string B have an equivalent pattern into a bigger string A. For example, if A="aabbccd" and B="xx", then it should print 3, since "aa", "bb", "cc" are all substrings of A which share the same pattern as B.
I have tried to pass the substrings as numbers, such as xx becomes "11" and do the same for string A, but I still can't get it to work. Any ideas? Length can be up to 10^7.
Here's the code for changing pattern:
void transform(int* dest, char* original, int len) {
int j=1;
Al[original[0]-'a']=j;
dest[0]=j;
j++;
for (int i=1;i<len;i++) {
if (Al[original[i]-'a']==0)
Al[original[i]-'a']=j++;
dest[i]=Al[original[i]-'a'];
}
}
Concept: Use Regular Expressions
You would need the following regular expression (\\w)\\1{(REPETITIONS-1)}
I don't know about C but Java provides a library to compile RegEx patterns. Here's a class that implements just what you want:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringPatternPermutation {
public static void main(String[] args) {
int REPETITIONS = 3;
String REGEX = "(\\w)\\1{" + (REPETITIONS-1) + "}";
String INPUT = "abbbbbbccddeffff";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
int count = 0;
while(m.find()){
String match = m.group();
System.out.println(match);
count++;
}
System.out.println(count);
}
}
Here's a test of the code above: https://ideone.com/5nztaa
Here's a useful website to test any RegEx: https://regexr.com/
Without Regular Expressions
public class StringPatternPermutation {
public static void main(String[] args) {
String a = "abjjjiixsssppw";
String b = "qwwwee";
String patternA = detectPattern(a);
String patternB = detectPattern(b);
System.out.println("-String A: " + a);
System.out.println("-Pattern A: " + patternA);
System.out.println("-String B: " + b);
System.out.println("-Pattern B: " + patternB);
System.out.println("-A contains B? " + patternA.contains(patternB));
int count = 0;
int index = 0;
while((index = patternA.indexOf(patternB)) != -1){
count++;
patternA = patternA.substring(index+1, patternA.length());
}
System.out.println("-Number of occurances: " + count);
}
private static String detectPattern(String a){
StringBuilder sb = new StringBuilder();
char prev = a.charAt(0);
int count = 1;
for(int i = 1; i < a.length(); i++){
char curr = a.charAt(i);
if(curr == prev)
count++;
else {
sb.append(count + ", ");
prev = curr;
count = 1;
}
if(i == a.length() - 1){
sb.append(count);
}
}
return sb.toString();
}
}
Test it on ideOne: https://ideone.com/w422Du

Storing each digit from double to an array

I am a newbie at this and I am not sure on how to go about to store the digits of a double to an array. I have this double value: 0120.1098
I want it to be stored as something like this:
value[1] = 0
value[2] = 1
value[3] = 2
value[4] = 0
value[5] = 1
`
and so on...
How do I do it?
I'm not sure if you really need to extract them, but as I don't know much more about your context, here you go.
You could turn it into a String, split it on . and iterate. This way you get two int arrays. One for the digits before the decimal and on for the digits after de decimal.
public static void main(String[] args) {
double d = 12323.213432;
String asString = String.valueOf(d);
String[] splitOnDecimal = asString.split("\\.");
int[] upperBound = getIntArray(splitOnDecimal[0]);
int[] lowerBound = getIntArray(splitOnDecimal[1]);
System.out.println(Arrays.toString(upperBound));
System.out.println(Arrays.toString(lowerBound));
}
private static int[] getIntArray(String numberString) {
int[] tmpArray = new int[numberString.length()];
for (int i = 0; i < numberString.length(); i++) {
tmpArray[i] = Integer.parseInt(numberString.substring(i, i + 1));
}
return tmpArray;
}
Try this, it will even show your zeroes:
String dbl = "0012300.00109800";
int dblArraylength = dbl.length();
char[] c = dbl.toCharArray();
int dotId= dbl.indexOf(".");
int a[] = new int[dblArraylength-1];
for(int i=0; i<dotId; i++){
a[i]=Integer.parseInt(Character.toString ((char)c[i]));
}
for(int i=dotId; i<a.length; i++){
a[i]=Integer.parseInt(Character.toString ((char)c[i+1]));
}
for(int i=0; i<a.length; i++){
System.out.println("a[" +i+ "] = " + a[i]);
}

String array error or bad declaring

public class Hotel{
int lb;
String nazwa;
String [] tablicaPok;
public Hotel (int lbH , String nazwaH){
nazwa = nazwaH;
lb = lbH;
String [] tablicaPok = new String [lb];
}
public String dajNazwe (){
return nazwa;
}
public int ilePokoi (){
return lb;
}
public void TestTab (){ co_w_tablicy
for(int i=0 ; i < lb ; i++)
tablicaPok[i] = ("element nr: " + i );
}
public void whatsInTab (){
for(int i =0 ; i < lb ; i++)
System.out.println ("el. nr : " + i + " ma wartosc " + tablicaPok[i]);
}
}
I created class Hotel with the ability to save some String to created in object Hotel array. When I tested it, it throws a NullPointerException. I'm not sure if I am testing that array badly or if it is declared incorrectly.
In your constructor, you should use
tablicaPok = new String [lb];
instead of
String [] tablicaPok = new String [lb];
so that you are referencing the same variable.
You should also initialize it so that when you call whatsInTab(), it will have something to show for it. Something like:
for(int i=0 ;i < lb ; i++){
tablicaPok[i] = "";
}

datatypes and arrays in java

Thoroughly confused on how to do this. What I want to do is to place the city with the lowest min, or max in the output. My understanding is you cannot throw a string in with another datatype in a method. How in the world can I match the name with the lowest temperature?
Lets say I want 3 cities:
I want to make the array 3 then:
Then I will add in the following cities, (Alanta, New York, Richmond)
The cities temperatures are (42.2, 98.8, -12.4)
Min is -12.4
Max is 98.8
That I have, how do I link Richmond's String that is stored in array[2] to temperature's double that is stored in array[2]? Any help is much appreciated.
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.lang.Math;
public class Ex9
{
public static void main(String[] args)
{
String message ="";
double min = 0, max = 0, avg = 0;
int counter = 1;
int numberOfCities = Integer.parseInt(JOptionPane.showInputDialog(null, "How many cities would you like to enter?"));
String[] nameOfCities = new String[numberOfCities];
double[] temperatureOfCities = new double[numberOfCities];
for (int i = 0; i < nameOfCities.length; i++)
{
nameOfCities[i] = JOptionPane.showInputDialog(null, "Please enter the name of city " +counter+" :");
temperatureOfCities[i] = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter the current temperature of the city " + counter +" :"));
message += "City name " + nameOfCities[i] + ".\n"
+ "Temperature of city " + temperatureOfCities[i] + " is degrees\n";
counter++;
}//end numberOfCities loop
if(
JOptionPane.showMessageDialog(null, message + "\nThe average temperature is " +findAvg(temperatureOfCities)+ "\n[Name of city] has the lowest temperature, which is " + findMin(temperatureOfCities) + "\n[Name of city] has the highest temperature, which is " + findMax(temperatureOfCities));
}//end main
public static double findAvg(double[] temperatureOfCities)
{
double sum =0;
for(int i=0;i<temperatureOfCities.length;i++)
{
sum += temperatureOfCities[i];
}
sum = sum/temperatureOfCities.length;
return sum;
}//end findAvg
public static double findMin(double[] temperatureOfCities)
{
double min=0;
for(int i =0; i <temperatureOfCities.length;i++)
{
if (temperatureOfCities[i] <= temperatureOfCities[0])
{
min = temperatureOfCities[i];
}
}//end for loop
return min;
}//end findMin
public static double findMax(double[] temperatureOfCities)
{
double max=0;
for(int i =0; i <temperatureOfCities.length;i++)
{
if (temperatureOfCities[i] >= temperatureOfCities[0])
{
max = temperatureOfCities[i];
}
}//end for loop
return max;
}//end findMax
}//end program
Two main approaches here:
1) The procedural approach - just pass both arrays around instead of just one array. If they're kept synchronized there's no problem - just use the same index for both.
2) The object oriented approach - Define a class TemperatureReading with double temperature and string cityName. Then you can make a TemperatureReading[] array and pass it around, and the data is naturally associated.
Change your findMin, findAvg, and findMax methods to return a composite Measurement object.
class Measurement {
final double temperature;
final String cityName;
Measurment(String cityName, double temperature)
{
this.temperature = temperature;
this.cityName = cityName;
}
}
The updated methods could look something like this:
public static Measurement findMax(String[] nameOfCities, double[] temperatureOfCities) {
double maxTemp=0;
String maxName=null;
for(int i =0; i <temperatureOfCities.length;i++)
{
if (temperatureOfCities[i] >= temperatureOfCities[0])
{
maxTemp = temperatureOfCities[i];
maxName = nameOfCities[i];
}
} //end for loop
return new Measurement(maxTemp, maxName);
}
Now you can use the results like this:
Measurement maxMeasurement = findMax(nameOfCities, temperatureOfCities);
System.out.println(maxMeasurement.cityName + "has a temperature of " + maxMeasurement.temperature);
Similar goes for findMin and findAvg.

Resources