What I want is if [1][0] is already in the list then if inputting [0][1] is considered as duplicate thus not adding it to the loop. That's the only thing that I wanted to accomplish and yet it seems impossible; at least for me.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class MatrixGraph{
List<List<Integer>> graph;
Scanner input = new Scanner(System.in);
ArrayList<Connection> Links = new ArrayList<Connection>();
boolean visited[];
int nodes;
int vertices;
int matrix[][];
class Node {
String name;
boolean visited;
ArrayList<Node> neighbors = new ArrayList<Node>();
Node(String name) {
this.name = name;
visited = false;
}
}
class Connection {
double fare;
Node source, destination;
Connection(Node source, Node destination) {
this.source = source;
this.destination = destination;
}
}
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of vertices");
int V = s.nextInt();
MatrixGraph amg = new MatrixGraph(V);
int n1 = V-1; int n2 = V*n1; int maxSize = n2/2;
while (true){
System.out.println("Enter the number of edges");
int E = s.nextInt();
if (E > maxSize){
System.out.println("Too Much Edges!");
continue;
}else{
System.out.print("\n");
for(int i=0;i<E;i++){
System.out.print("Source: ");
int mark = s.nextInt();
System.out.print("Destination: ");
int mac = s.nextInt();
if (mark == mac) {
System.out.println("\nERROR TRAPPED!!\nNo Loops Allowed Here!\nAdd New Edge!");
i--;
continue;
} else if(mark > (V-1)||mac > (V-1)) {
i--;
System.out.println("\nLOL No\n");
}
amg.addEdge(mark,mac);
amg.addEdge1(mark,mac);
}
}
}
}
MatrixGraph(int vertices){
graph = new ArrayList<>();
visited = new boolean[vertices];
this.vertices=vertices;
matrix=new int[vertices][vertices];
for (int i = 0; i < vertices; i++){
graph.add(i, new ArrayList<>());
}
}
public void addEdge(int source,int destination){
matrix[source][destination]= 1;
matrix[destination][source]= 1;
}
public void addEdge1(int a, int b) {
graph.get(a).add(b);
graph.get(b).add(a);
}
}
Related
I have an array of 15 Student objects that consist of an int (student ID) and an array (scores for 5 lab assignments). I am required to calculate the Low, High, and Avg scores for each of the 5 labs. The only way I can think of doing this is looking at all the arrays by columns, but my arrays are a row for each student. How would I go about doing these calculations on these arrays.
Included is a Util class which the Student object array comes from and a Student class to define the object. I only need help with the Statistics class provided.
Any help would be greatly appreciated!
Util.class:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Util {
public static Student[] readFile(String fileName) {
Student studentArray[]=new Student[15];
try{
FileReader file = new FileReader("studentData.txt");
BufferedReader buff = new BufferedReader(file);
String line;
line = buff.readLine();
int index=0;
while(line != null){
System.out.println(line);
if(index>14){
break;
}
line = buff.readLine();
String[] result = line.split("\\s");
int sid = Integer.parseInt(result[0]);
int scores[] = new int[5];
for(int x=1;x<result.length;x++){
scores[x-1] = Integer.parseInt(result[x]);
}
Student myCSC20Student = new Student(sid, scores);
studentArray[index++] = myCSC20Student;
}
}
catch (IOException e){
System.out.println("Error: " + e.toString());
}
return studentArray;
}
}
Student.class:
import java.io.*;
import java.util.*;
public class Student {
final int LABS = 5;
private int SID;
private int scores[] = new int[LABS];
public Student(int sid, int[] scores)
{
this.SID=sid;
this.scores = scores;
}
//getters and setters for SID and scores
public int getID() {
return SID;
}
public void setID(int x) {
this.SID = x;
}
public int[] getScore() {
return scores;
}
}
Statistics.class:
import java.io.*;
import java.util.*;
public class Statistics {
final int LABS = 5;
public int[] lowscores = new int[LABS];
private int[] highscores = new int[LABS];
private float[] avgscores = new float[LABS];
public static void main(String args[]) {
Student[] studArr = Util.readFile("studentData.txt");
System.out.println("");
for(int i=0; i<=studArr.length-1; i++){
System.out.println(Arrays.toString(studArr[i].getScore()));
}
}
void calculateLow(Student[] a){
}
void calculateHigh(Student[] a){
}
void calculateAvg(Student[] a){
}
}
Output Class:
import java.util.*;
public class Output{
public static void main(String[] args){
Student[] studArr = Util.readFile("studentData.txt");
Statistics statistics = new Statistics();
statistics.calculateLow(studArr);
statistics.calculateHigh(studArr);
statistics.calculateAvg(studArr);
System.out.println("Low scores:");
System.out.println(Arrays.toString(statistics.getLowscores()));
System.out.println("High scores:");
System.out.println(Arrays.toString(statistics.getHighscores()));
System.out.println("Average scores:");
System.out.println(Arrays.toString(statistics.getAvgscores()));
}
}
Output of scores of all 15 students for the 5 labs
#Bogdan-Lukiyanchuk provided a solution that utilizes Java streams. I am of the impression the assignment is designed to only use loops and arrays. As such, a pointer to the solution is something along the lines of:
void calculateLow(Student[] a) {
// if we don't have any students, then just leave
if (a == null || a.length == 0) {
return;
}
// set to the maximum score one could possibly have
int lowScore = Integer.MAX_INT;
Student lowPersonOnTotem = null;
// process all of the students
for (Student student : a) {
int[] scores = student.getScore();
// loop over all of the scores; if the score is lower than any
// previous, update the lowScore and who had it
for (int score : scores) {
if (score < lowScore) {
lowScore = score;
lowPersonOnTotem = student;
}
}
}
System.out.printf("Lowest score of all students is %d achieved by %d\n",
lowScore, lowPersonOnTotem.getId());
}
Now, following from the critique by #markspace in the comments, I would think having calculateLow() return a value and then have the display elsewhere would be most appropriate, but the method was marked as void in the OP's example.
The other methods are essentially the same loop, but the math changes.
import java.util.*;
public class Statistics {
final int LABS = 5;
public int[] lowscores = new int[LABS];
private int[] highscores = new int[LABS];
private float[] avgscores = new float[LABS];
public static void main(String args[]) {
Student[] studArr = Util.readFile("studentData.txt");
System.out.println();
for(int i=0; i<=studArr.length-1; i++){
System.out.println(Arrays.toString(studArr[i].getScore()));
}
Statistics statistics = new Statistics();
statistics.calculateLow(studArr);
statistics.calculateHigh(studArr);
statistics.calculateAvg(studArr);
System.out.println("Low scores:");
System.out.println(Arrays.toString(statistics.getLowscores()));
System.out.println("High scores:");
System.out.println(Arrays.toString(statistics.getHighscores()));
System.out.println("Average scores:");
System.out.println(Arrays.toString(statistics.getAvgscores()));
}
public void calculateLow(Student[] a){
for (int i = 0; i < LABS; i++) {
final int lab = i;
lowscores[lab] = Arrays.stream(a)
.mapToInt(student -> student.getScore()[lab])
.min()
.orElse(0);
}
}
public void calculateHigh(Student[] a){
for (int i = 0; i < LABS; i++) {
final int lab = i;
highscores[lab] = Arrays.stream(a)
.mapToInt(student -> student.getScore()[lab])
.max()
.orElse(0);
}
}
public void calculateAvg(Student[] a){
for (int i = 0; i < LABS; i++) {
final int lab = i;
avgscores[lab] = (float) Arrays.stream(a)
.mapToInt(student -> student.getScore()[lab])
.average()
.orElse(0);
}
}
public int[] getLowscores() {
return lowscores;
}
public int[] getHighscores() {
return highscores;
}
public float[] getAvgscores() {
return avgscores;
}
}
I have used disjoint set concept to solve this problem. Starting with all milkmen as visited, whenever a new person can be reached with new branch, he is marked as visited. I have already tested following edge cases:
There is no milkmen in the city
Everyone is milkman
Some milkman is not connected to anyone
Some person is not connected to anyone
Multiple paths between 2 people
Milkmen and people are forming disjoint set
Still i am getting WA. Any idea about missing case?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by VIVEK VERMA on 9/25/2016.
*/
public class SpojIITWPC4I {
public static void main(String[] arge) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
for (int t = 0; t < T; t++) {
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
int n = Integer.parseInt(tokenizer.nextToken());
int m = Integer.parseInt(tokenizer.nextToken());
int totalIncludedNodes = 0;
ManNode[] people = new ManNode[n];
Queue<ManLink> links = new PriorityQueue<>();
tokenizer = new StringTokenizer(reader.readLine());
for(int i=0;i<n;i++){
int val=Integer.parseInt(tokenizer.nextToken());
people[i] = new ManNode(i);
if(val==1){
people[i].isIncluded = true;
totalIncludedNodes++;
}
}
for(int i = 0; i<m;i++){
tokenizer = new StringTokenizer(reader.readLine());
int start = Integer.parseInt(tokenizer.nextToken()) -1;
int destination = Integer.parseInt(tokenizer.nextToken()) -1;
int value = Integer.parseInt(tokenizer.nextToken());
ManLink link = new ManLink(people[start], people[destination], value);
people[start].AddChild(link);
people[destination].AddChild(link);
if(people[start].isIncluded ^ people[destination].isIncluded){
links.add(link);
}
}
int minCost = 0;
while(!links.isEmpty() && totalIncludedNodes <n){
ManLink link = links.poll();
ManNode nextAddedNode = (link.source.isIncluded==true?link.destinationNode:link.source);
if(nextAddedNode.isIncluded){
continue;
}
minCost += link.value;
nextAddedNode.isIncluded = true;
totalIncludedNodes++;
for(int i=0;i<nextAddedNode.children.size();i++){
if((nextAddedNode.isIncluded ^ nextAddedNode.children.get(i).source.isIncluded)
|| (nextAddedNode.isIncluded ^ nextAddedNode.children.get(i).destinationNode.isIncluded)){
links.add(nextAddedNode.children.get(i));
}
}
}
if(totalIncludedNodes == n){
System.out.println(minCost);
}else{
System.out.println("impossible");
}
}
}
}
class ManNode{
boolean isIncluded = false;
List<ManLink> children = new ArrayList<>();
int index;
ManNode(int index){
this.index = index;
}
void AddChild(ManLink link){
children.add(link);
}
}
class ManLink implements Comparable{
ManNode destinationNode, source;
int value;
ManLink(ManNode source, ManNode node, int value){
this.source = source;
this.destinationNode = node;
this.value = value;
}
#Override
public int compareTo(Object o) {
return this.value - ((ManLink)o).value;
}
}
I have a problem with implementation of merge sort in java. I am looking for the error almost week unfortunately without result. ArrayList at the entrance is the same as the output.
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
ArrayList<Integer> arrayListA = new ArrayList<Integer>();
ArrayList<Integer> arrayListB = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int firstIndexOfArrayList = 0;
private int lastIndexOfArrayListA;
private int lastIndexOfArrayListB;
public void Scal(ArrayList<Integer> basicArrayList, int p, int q, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListA = q;
this.lastIndexOfArrayListB = r;
int numberOfElementsArrayListA = lastIndexOfArrayListA
- firstIndexOfArrayList + 1;
int numberOfElementsArrayListB = lastIndexOfArrayListB
- lastIndexOfArrayListA;
for (int i = 0; i < numberOfElementsArrayListA; i++) {
arrayListA.set(i, basicArrayList.get(firstIndexOfArrayList + i));
}
for (int j = 0; j < numberOfElementsArrayListB; j++) {
arrayListB.set(j, basicArrayList.get(lastIndexOfArrayListA + j));
}
arrayListA.add(Integer.MAX_VALUE);
arrayListB.add(Integer.MAX_VALUE);
int i = 0;
int j = 0;
for (int k = firstIndexOfArrayList; k <= lastIndexOfArrayListB; k++) {
if (arrayListA.get(i) <= arrayListB.get(j)) {
basicArrayList.set(k, arrayListA.get(i));
i = i + 1;
} else {
basicArrayList.set(k, arrayListB.get(j));
j = j + 1;
}
}
}
public void MergeSort(ArrayList basicArrayList, int p, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListB = r;
if (firstIndexOfArrayList < lastIndexOfArrayListB) {
int lastIndexOfArrayListA = (firstIndexOfArrayList + lastIndexOfArrayListB) / 2;
MergeSort(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA);
MergeSort(basicArrayList, lastIndexOfArrayListA + 1,
lastIndexOfArrayListB);
Scal(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA,
lastIndexOfArrayListB);
}
}
public void setSize() {
System.out.println("Enter the number of elements to sort: ");
this.lastIndexOfArrayListB = input.nextInt();
}
public int getSize() {
return lastIndexOfArrayListB;
}
public void setData() {
System.out.println("Enter the numbers: ");
for (int i = 0; i < lastIndexOfArrayListB; i++) {
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable() {
System.out.println(basicArrayList.toString());
}
public static void main(String[] args) {
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.MergeSort(output.basicArrayList,
output.firstIndexOfArrayList, (output.getSize() - 1));
output.getTable();
}
}
In terms of fixing your code I had a crack at it and as far as I can tell this seems to work. To do this a lot of your code had to be changed but it does now sort all Integers properly
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int numbersToSort;
public void doMergeSort(int firstIndexOfArrayList,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
if(firstIndexOfArrayList<lastIndexOfArrayListB && (lastIndexOfArrayListB-firstIndexOfArrayList)>=1)
{
int mid = (lastIndexOfArrayListB + firstIndexOfArrayList)/2;
doMergeSort(firstIndexOfArrayList, mid, arrayList);
doMergeSort(mid+1, lastIndexOfArrayListB, arrayList);
Scal(firstIndexOfArrayList,mid,lastIndexOfArrayListB, arrayList);
}
}
public void Scal(int firstIndexOfArrayList,int lastIndexOfArrayListA,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
ArrayList<Integer> mergedSortedArray = new ArrayList<Integer>();
int leftIndex = firstIndexOfArrayList;
int rightIndex = lastIndexOfArrayListA+1;
while(leftIndex<=lastIndexOfArrayListA && rightIndex<=lastIndexOfArrayListB)
{
if(arrayList.get(leftIndex)<=arrayList.get(rightIndex))
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
else
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
}
while(leftIndex<=lastIndexOfArrayListA)
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
while(rightIndex<=lastIndexOfArrayListB)
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
int i = 0;
int j = firstIndexOfArrayList;
while(i<mergedSortedArray.size())
{
arrayList.set(j, mergedSortedArray.get(i++));
j++;
}
}
public void setSize()
{
System.out.println("Enter the number of elements to sort: ");
this.numbersToSort = input.nextInt();
}
public int getSize()
{
return numbersToSort;
}
public void setData()
{
System.out.println("Enter the numbers: ");
for (int i = 0; i < numbersToSort; i++)
{
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable()
{
System.out.println(basicArrayList.toString());
}
public void runSort(ArrayList<Integer> arrayList)
{
doMergeSort(0, this.numbersToSort-1, arrayList);
}
public static void main(String[] args)
{
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.runSort(output.basicArrayList);
output.getTable();
}
}
Try this code. The following code takes an ArrayList input and outputs an ArrayList as well so it still works along the same basis of your code. The actual sort is handled in a different class MergeSort and is passes into ForMergeSort. Hope this helps
MergeSort.java
public class MergeSort
{
private int[] array;
private int[] tempMergArr;
private int length;
public void sort(int[] inputArr)
{
}
public int[] getSortedArray(int[] inputArr)
{
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
for(int i=0;i<length;i++)
{
int correctNumber = i+1;
System.out.println("Value "+correctNumber+" of the sorted array which was sorted via the Merge Sort is: "+inputArr[i]);
}
return inputArr;
}
private void doMergeSort(int lowerIndex, int higherIndex)
{
if (lowerIndex < higherIndex)
{
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex)
{
for (int i = lowerIndex; i <= higherIndex; i++)
{
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex)
{
if (tempMergArr[i] <= tempMergArr[j])
{
array[k] = tempMergArr[i];
i++;
}
else
{
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle)
{
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
ForMergeSort.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ForMergeSort
{
ArrayList<Integer> arrayList = new ArrayList<Integer>();
ArrayList<Integer> sortedArrayList = new ArrayList<Integer>();
MergeSort mS = new MergeSort();
public void buildArrayList()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements to sort: ");
int toSort = input.nextInt();
System.out.println("Enter the numbers: ");
for(int i =0; i<toSort; i++)
{
int number = input.nextInt();
arrayList.add(number);
}
}
public void runMergeSort(ArrayList<Integer> arrayList)
{
int[] arrayOfValues = new int[arrayList.size()];
int i = 0;
for(int a:arrayList)
{
arrayOfValues[i] = a;
i++;
}
MergeSort mS = new MergeSort();
for(int intOfArray:mS.getSortedArray(arrayOfValues))
{
sortedArrayList.add(intOfArray);
}
System.out.println(sortedArrayList.toString());
}
public static void main(String[] args)
{
ForMergeSort fMS = new ForMergeSort();
fMS.buildArrayList();
fMS.runMergeSort(fMS.arrayList);
}
}
I'm trying to use insertion sort to sort for the batting average of the players. I get an error message "The method get(int) in the type java.util.ArrayList is not applicable for the arguments (double)" on the lines of S.get(outer) and S.get(inner - 1)
What am I doing wrong?
How can I fix this?
import java.util.*;
import java.io.*;
class menu {
public static void main (String [] arg) throws IOException
{
PlayerRip.PlayerInfo obj5 = new PlayerRip.PlayerInfo();
ArrayList<Player> obj6 = new ArrayList<Player>();
MainMenu(obj5, obj6);
}
public static void MainMenu(PlayerRip P, ArrayList<Player> S) throws IOException
{
Scanner keyboard = new Scanner(System.in);
int response = 0;
int response2 = 0;
ArrayList<Player> obj1 = new ArrayList<Player>();
obj1.add(new Player("Agostini", "Aldo", "Pitcher", 170, 20, 72, 12, 6, 1, 1, 0));
do
{
System.out.println("1. Open A file:");
System.out.println("7. Exit the program");
response = keyboard.nextInt();
switch (response)
{
case 1:
{
openFile(obj1);
do
{
System.out.println("2. Display all players");
System.out.println("3. Enter player's Height");
System.out.println("4. Sort all players alphabetically by Surname");
System.out.println("5. Sort all players by batting average");
System.out.println("6. Delete a player by selecting the player's surname from a list");
System.out.println("7. Add a player to the stats");
System.out.println("8. Save stats to a file");
System.out.println("9. Exit the program");
response2 = keyboard.nextInt();
switch (response2)
{
case 2:
{
displayInfo(obj1);
break;
}
case 3:
{
changeHeight(obj1);
break;
}
case 4:
{
BubbleSort(obj1);
break;
}
case 5:
{
break;
}
case 6:
{
deletePlayerInfo(obj1);
break;
}
case 7:
{
addPlayerInfo(obj1);
break;
}
case 8:
{
saveFile(obj1);
break;
}
case 9:
{
System.exit(0);
break;
}
}
} while (response2 != 9);
break;
}
case 7:
{
System.exit(0);
break;
}
}
} while (response != 1 || response != 7); // End of switch statement
}
public static void displayInfo(ArrayList<Player> S) {
System.out.printf("%10s %10s %10s \t %4s %4s \t %4s \t %4s %4s \t %4s %4s %4s \n", "Surname", "GivenName", "Postition", "Height(cm)", "Hits", "AtBats", "Singles", "Doubles", "Triples", "HomeRuns", "Batting Average");
for (int index = 0; index < S.size(); index++)
S.get(index).displayInfo();
}
public static void openFile(ArrayList<Player> S) throws IOException // This method allows the oepning of files into the program
{
Scanner userInput = new Scanner(System.in);
String fileName;
S.removeAll(S); // Empties the list readies it for a new oned
System.out.println("Enter a file name to open: ");
fileName = userInput.next().trim();
File file = new File(fileName);
if (file.exists()) // Checks whether or not the file exists in the directory
{
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext())
{
S.add(new Player(fileInput.next(), fileInput.next(), fileInput.next(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextDouble())); // If it exists it adds the token values into the respective lists
}
fileInput.close(); // Closes further file input
}
else // Error message incase the file-name is not valid
System.out.println("FILE NOT FOUND");
}
public static void saveFile(ArrayList<Player> S) throws IOException // This method allows for the saving of values to an external file
{
Scanner inputInfo = new Scanner(System.in);
String fileName;
System.out.println("Enter a file name to save the info with:");
fileName = inputInfo.next().trim();
File file = new File(fileName);
PrintStream writeFile = new PrintStream(file);
for (int i = 0; i < S.size(); i++) // Gathers all values and prints them to the file in their respective format
{
writeFile.print(S.get(i).getName() + " ");
writeFile.print(S.get(i).getName2() + " ");
writeFile.print(S.get(i).getPosition() + " ");
for (int j = 0; j < 7; j++)
writeFile.print(S.get(i).getMark(j) + " ");
for (int j = 0; j < 1; j++)
writeFile.print(S.get(i).getBatAvg(j));
writeFile.println(" ");
}
writeFile.close(); // Stops any further writing to the file
}
public static void deletePlayerInfo(ArrayList<Player> S) // THis method allows the user to delete any player within the list
{
int deleteIt = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please select the number of the player to be deleted: ");
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
deleteIt = keyboard.nextInt();
S.remove(deleteIt);
}
public static void addPlayerInfo(ArrayList<Player> S) // This method allows the user to add a new player to the list
{
String firstName = "";
String surName = "";
String posName = "";
int heightVal = 0;
int hitsVal = 0;
int atBatsVal = 0;
int singVal = 0;
int doubVal = 0;
int tripVal = 0;
int homeVal = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Enter the surname and name of the new player: ");
System.out.println("Surname: ");
surName = keyboard.nextLine();
System.out.println("Name: ");
firstName = keyboard.nextLine();
System.out.println("Enter the position of the new player: ");
System.out.println("Position: ");
posName = keyboard.nextLine();
System.out.println("Enter the height of the new player: ");
heightVal = keyboard.nextInt();
System.out.println("Enter the batting statistics: ");
System.out.println("Hits: ");
hitsVal = keyboard.nextInt();
System.out.println("AtBats: ");
atBatsVal = keyboard.nextInt();
System.out.println("Singles: ");
singVal = keyboard.nextInt();
System.out.println("Doubles: ");
doubVal = keyboard.nextInt();
System.out.println("Triples: ");
tripVal = keyboard.nextInt();
System.out.println("HomeRuns: ");
homeVal = keyboard.nextInt();
S.add(new Player(surName, firstName, posName, heightVal, hitsVal, atBatsVal, singVal, doubVal, tripVal, homeVal, 0));
}
public static void changeHeight(ArrayList<Player> S)
{
int playerSel = 0;
int newHeight = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Select a player to enter the height for: ");
do
{
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
playerSel = keyboard.nextInt();
System.out.println("Enter the height for this character: ");
newHeight = keyboard.nextInt();
if (newHeight < 125 && newHeight > 240)
{
System.out.println("WRONG! TRY AGAIN!");
}
else
{
}
} while (newHeight >= 125 && newHeight <= 240);
}
public static void BubbleSort(ArrayList<Player> S){
Player strTemp;
int i = 0;
boolean isSorted = false;
while(i < S.size()&&isSorted==false)
{
isSorted = true;
for(int j = 0; j < (S.size()-1)-i;j++)
{
if(S.get(j).getName().compareToIgnoreCase(S.get(j+1).getName())>0){
strTemp = S.get(j);
S.set(j,S.get(j+1));
S.set(j+1,strTemp);
isSorted = false;
}
}
i++;}
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
class PlayerRip {
public String name;
public String name2;
public String position;
public int [ ] mark = new int[7];
public double [ ] batAvg = new double[1];
static class PlayerInfo extends PlayerRip
{
PlayerInfo() {
this.name = "-1";
this.name2 = "-1";
this.position = "-1";
for (int i=0; i < mark.length; i++)
mark[i] = -1;
}
PlayerInfo(String nam, String nam2, String pos, int a, int b, int c, int d, int e, int f, int g, double h) {
this.name = nam;
this.name2 = nam2;
this.position = pos;
this.mark[0] = a; this.mark[1] = b; this.mark[2] = c; this.mark[3] = d; this.mark[4] = e; this.mark[5] = f; this.mark[6] = g;
batAvg[0] = (((double)mark[1] / (double)mark[2]) * 100);
}
public void setName(String nam) { name = nam; }
public void setName2(String nam2) { name2 = nam2; }
public void setPosition(String pos) { position = pos; }
public void setMark(int index, int mark) { this.mark[index] = mark; }
public void setBatAvg(int index, double batAvg) {this.batAvg[index] = batAvg;}
public String getName() { return this.name; }
public String getName2() { return this.name2; }
public String getPosition() { return this.position; }
public double getBatAvg() { return this.batAvg[0];}
public int getMark(int index) { return this.mark[index]; }
public void setHeight(int index, int mark) { this.mark[index] = mark; }
public int getHeight(int index) { return this.mark[0]; }
public void setHits (int index, int mark) { this.mark [index] = mark; }
public int getHits (int index) { return this.mark [1]; }
public void setAtBats (int index, int mark) { this.mark [index] = mark; }
public int getAtBats(int index) { return this.mark [2]; }
public void setSingles (int index, int mark) { this.mark [index] = mark; }
public int getSingles (int index) { return this.mark [3] ; }
public void setDoubles (int index, int mark) { this.mark [index] = mark; }
public int getDoubles (int index) { return this.mark [4] ; }
public void setTriples (int index, int mark) { this.mark [index] = mark; }
public int getTriples (int index) { return this.mark [5] ; }
public void setHomeRuns (int index, int mark) { this.mark [index] = mark; }
public int getHomeRuns (int index) { return this.mark [6] ; }
}
}
sorry for format im new to the site
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
is the specific area of problems
S.get() and S.set() take a int variable so cast inner to a int.
You defined inner as a double, and in Java, when you do math with a double and an int (such as inner - 1), you'll get a double as a result. This page has a fairly good explanation.
Then when you say S.get(inner - 1), you're saying to use a double as an the index in the ArrayList. The documentation for ArrayList.get says that you can only use an int as an index, and that's why you're getting a compiler error. You're also only allowed to use an int as the index for set, so that's why the compiler would complain about S.set(inner, ...).
You could just cast inner to an int, but it would be much better to declare it as an int in the first place since there's no reason it needs to be a double.
I try to make an array of nodes with a node on a specific place in the array.
For example:
I add a node in the array and set its number to 1.
I add another node in the array on the next position and set its number to 2.
Both nodes got the number 2 now.
Sample of the code:
public static String run(InputStream in) {
Scanner sc = new Scanner(in);
//indicating values
sc.nextInt(); /* int vertices = */
int edge = sc.nextInt();
int start = sc.nextInt();
int end = sc.nextInt();
if (start == end) {
sc.close();
Path = "yes";
} else {
nodes = new Node[edge + 1];
for (int i = 1; i < edge; i++) {
//Node values
int number = sc.nextInt();
int next = sc.nextInt();
sc.nextInt(); /* int distance = */
Node node = new Node(number, next);
if (nodes[number] == null) {
nodes[number] = (node);
} else {
nodes[number].addChild(next);
}
}
hasPath(nodes[start], end);
}
sc.close();
return Path;
}
Sample of the Node code:
import java.util.ArrayList;
public class Node {
private ArrayList<Integer> childs = new ArrayList<Integer>();
private static int number;
public Node(int n, int next){
number = n;
childs.add(next);
}
public int getNumber(){
return number;
}
public void addChild(int child){
childs.add(child);
}
Can anyone please help me?
The problem is with declaring the number member static. This means there's only one such member for the Node class, instead of each instance having its own member. Just define it as an instance variable, and you should be fine:
public class Node {
private ArrayList<Integer> childs = new ArrayList<Integer>();
private int number; // Note the static was removed
// rest of the class