The Code below I tried got to work correctly. When I go to "Run As" in Eclipse, the Console shows nothing and the output is blank. Please help. NOTE I took out the public class & import java because the post wasn't loading the code correctly.
public static void main(String[] args ) {
// Create new Scanner
Scanner input = new Scanner(System.in);
// Set number of students to 10
int numStudents = 10;
// Note
int [][] studentData = new int[numStudents][1];
// loop
for (int i = 0; i > numStudents; i++) {
// Note
boolean classesValidity = true ;
while (classesValidity == false) {
System.out.print("Enter classes and graduation year for student’" +
(i + 1) + " : " );
int numClasses = input.nextInt();
studentData [i][0] = numClasses;
int gradYear = input.nextInt();
studentData [i][1] = gradYear; }
for (int i1 = 0; i > numStudents; i ++) { System.out.println("\n Student " + ( i ) + " needs " +
studentData [i][0]*3 + " credits to graduate in " + studentData [i][1]); }}}}
classesValidity is initialized with true and remains unchanged. In turn the while loop is never executed and the program only iterates through studentData without operating on it.
Related
I'm trying to set up a program where the user(student) inputs how many courses they have left to graduate and and how many classes the intend to take per terms and the program will form this data into an array and print out how many terms they have left. The user is not allowed to take more than 5 courses per term so I want to prompt the user that the number they input is incorrect while also looping that input for that specific student without have to close the console and re-run the program. I've tried placing a while(true){} loop there in order to loop it but i can't seem to get the loop i desire.
I've tried placing the while(true){} loop in multiple spots of the code and can't get the desired result.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] students = new int[10][2];
for (int i = 0; i < students.length; i++) {
System.out.println("Enter classes remaining and taking each term for student " + (i + 1) + ": ");
for (int j = 0; j < students[i].length; j++) {
students[i][j] = input.nextInt();
if (students[i][1] > 5)
System.out.println("The number of classes per term for student " + (i + 1) + " is invalid.");
}
}
System.out.println();
for (int i = 0; i < students.length; i++) {
System.out.println("Student " + (i + 1) + " has " + (int) Math.round(students[i][0] / students[i][1]) + " terms left to graduate.");
}
}
I expect the output for the first input to print","The number of class per term for student n is invalid." and repeat the prompt to enter the numbers for that same student n without proceeding to the next student input.
Here is the updated one based on your new comments. You should be good from here, make changes whatever you need.
public class StudentInfo
{
public static int totalStudents = 6;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[][] Students = new int[totalStudents][3];
// Student[i][0] will hold the Remaining classes.
// Student[i][1] will hold the Classes per semester and
// Student[i][2] will hold the number of total Semesters to complete all courses.
for (int i = 0; i < totalStudents; i++)
{
System.out.print("\n\nEnter the information for " + (i + 1) + "-th student.");
System.out.print("\n\nEnter the total number of remaining courses: ");
Students[i][0] = input.nextInt();
System.out.print("\nEnter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
while (Students[i][1] > 5)
{
System.out.println("\nStudents are not allowed to take more than 5 classes per semester.");
System.out.print("Enter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
}
int ts = Students[i][0] / Students[i][1];
if (Students[i][0] % Students[i][1] != 0)
ts++;
Students[i][2] = ts;
System.out.println("\nThis student needs a total of " + ts + " semesters to finish all courses.");
}
input.close();
}
}
public static void main(String[] args) {
//scanner library
Scanner input = new Scanner (System.in);
//Initialize array
int[][] students = new int [10][2];
//iterate scanner and condition loop
for(int i=0; i<students.length; i++){
System.out.print("Enter classes remaining and taking each term for student "+ (i+1) +": ");
for (int j=0; j<students[i].length;j++){
students[i][j]= input.nextInt();
}
while(students [i][1] > 5) {
System.out.println("The number of classes per term for student " + (i+1) + " is invalid.");
i--;
break;
}
}
System.out.println();
//Print out results compiled from array
for(int i =0; i<students.length; i++) {
System.out.println("Student "+(i+1)+" has "+ (int) Math.ceil((double)students[i][0]/students[i][1]) + " terms left to graduate.");
}
}
What I have is a program that will read a text file that has data from a file that is in the format
`FootballTeamName1 : FootballTeamName2 : FootballTeam1Score : FootballTeam2Score
Currently it reads in the file and will split it at each colon what I want to know is how would I make it so that each time it comes across a name then it will add that name to the list if it doesn't already exist or if it does then it will not create a duplicate value rather it will add the values to the values that already exist for that teams name.
I currently have a program that can get the values for when you search for a team but what I want to do is make it so that it is possible when the user does not specify a team then it will make it so that it will return the results for all of the teams. Here is what I have currently which asks for the location of the file and asks the user for specifying a file which works but I'm not sure how to do what I want.
import java.awt.Desktop;
import java.io.*;
import java.util.*;
public class reader {
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
Scanner scanner = new Scanner(System.in);
System.out.println("Enter filename");
String UserFile = sc.nextLine();
File file = new File(UserFile);
if(!file.exists()) {
continue;
}
if(UserFile != null && !UserFile.isEmpty()){
System.out.println("Do you want to generate plain (T)ext or (H)TML");
String input = scanner.nextLine();
if ( input.equalsIgnoreCase("H") ) {
processFile(UserFile) ; }
else if ( input.equalsIgnoreCase("T")){
processFile(UserFile);
}
else{
System.out.println("Do you want to generate plain (T)ext or (H)TML");
}
}
}
}
//checks how the user wants the file to be displayed
private static void processFile(String UserFile) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
int gamesplayed = 0;
int gs = 0;
int gc = 0;
int w = 0;
int d = 0;
int l = 0;
String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.
Scanner s = new Scanner(new BufferedReader(
new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name of the team you want the results for");
String input = scanner.nextLine();
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
if ( input.equalsIgnoreCase(hteam)){
gamesplayed = gamesplayed + 1;
gs = gs + hscore;
gc = gc + ascore;
if (hscore > ascore)
w = w + 1;
else if (ascore > hscore)
l = l + 1;
else
d = d + 1;
}
else if (input.equalsIgnoreCase(ateam)){
gamesplayed = gamesplayed + 1;
gs = gs + ascore;
gc = gc + hscore;
if (hscore < ascore)
w = w + 1;
else if (ascore < hscore)
l = l + 1;
else
d = d + 1;
}
}
}
System.out.println(input + newLine + "--------------------------" + newLine + "Games played: " + gamesplayed + newLine + "Games Won: " + w + newLine + "Games Drawn: " + d + newLine + "Games Lost: " + l + newLine + "Goals For: " + gs + newLine + "Goals Against: " + gc);
}
}
If you want no duplicate elements in your collection use a Set. A Set is a collection that contains no duplicate elements (doc here).
Sounds like you want a Map from Team to Score, where if the team already exists, then get the value from the map, and and the score to that.
You can add the entries into a Set (or if you want them sorted - SortedSet). Since Set only holds unique values - you'll always have only one "copy" of each value.
For reference, the following code uses 5 values, but the set will have only 3 (unique) values:
String str = "A : B : C : B : A";
String[] vals = str.split(":");
SortedSet<String> myVals = new TreeSet<String>();
for(String val : vals)
{
myVals.add(val.trim());
}
System.out.println("Set size: " + myVals.size());
this code is to be used to write the data inserted in to a file
when the loop runs the second student dont get entered i dont know why
this keeps getting stuck at the second student and i have been working on this for hours
import java.util.Scanner;
import java.io.*;
class wonder
{
public static void main(String args[]) throws IOException
{
Scanner c = new Scanner(System.in);
FileWriter ww = new FileWriter("D:\\student details.txt");
BufferedWriter o = new BufferedWriter(ww);
int counter = 0 ;
int stnum = 1;
while(counter < 4)
{
String name = "";
int marks = 0;
System.out.print("Enter student " + stnum + " name : " );
name = c.nextLine();
System.out.print("Enter marks : ");
marks = c.nextInt();
ww.write(stnum + " " + name + " " + marks );
ww.close();
counter++;
stnum++;
}
}
}
You close your FileWriter in each iteration of your while loop... what did you think would happen?
you close the writer in the loop, move the close statement outside of the loop
ww.close();
Things to do
put ww.close(); outside the while loop
change c.nextLine(); to c.next();
import java.util.Scanner;
import java.io.*;
class wonder
{
public static void main(String args[]) throws IOException
{
Scanner c = new Scanner(System.in);
FileWriter ww = new FileWriter("D:\\student details.txt");
BufferedWriter o = new BufferedWriter(ww);
int counter = 0 ;
int stnum = 1;
while(counter < 4)
{
String name = "";
int marks = 0;
System.out.print("Enter student " + stnum + " name : " );
name = c.next();
System.out.print("Enter marks : ");
marks = c.nextInt();
ww.write(stnum + " " + name + " " + marks );
counter++;
stnum++;
}
ww.close();
}
}
I wrote a small program consisting of two classes. I am trying to call the methods from the second class but I get an error.
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems: The method getSum(int[]) is undefined for the type
UserInteraction The method getAverage(int[]) is undefined for the type
UserInteraction at UserInteraction.main(UserInteraction.java:66)
Here's the code of the first class:
import java.util.Scanner;
public class UserInteraction {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int choice = 0;
String[] subjects = new String[10];
int grades[] = new int[10];
double sum = 0.0;
Grades method = new Grades();
do
{
System.out.println("1. Enter a course name and a grade");
System.out.println("2. Display all grades");
System.out.println("3. Calculate the average grade");
System.out.println("4. Exit program");
choice = scan.nextInt();
if ( choice == 1 )
{
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Enter 10 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 10; i++ )
{
System.out.println("Subject:");
String temp = scansubjects.nextLine();
subjects[i] = temp.toLowerCase();
System.out.println("Grade:");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length - 1 ) )
{
System.out.println("Thank you!");
System.out.println();
}
}
}
if ( choice == 2 )
{
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for(int p = 0; p < subjects.length; p++)
{
System.out.println(subjects[p] + "\t" + "\t" + grades[p]);
}
}
if ( choice == 3 )
{
System.out.println("Total of grades: " + getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + getAverage(grades));
System.out.println();
}
} while ( choice != 4);
}
}
And the second class is:
public class Grades {
public static double getAverage(int[] array)
{
int sum = 0;
for(int i : array) sum += i;
return ( ( double ) sum )/array.length;
}
public static double getSum(int[] array)
{
int sum = 0;
for (int i : array)
{
sum += i;
}
return sum;
}
}
You don't need this, because it only has static methods:
Grades method = new Grades(); // <-- delete this line
To call static methods they must be preceded with their class name like this:
System.out.println("Total of grades: " + Grades.getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + Grades.getAverage(grades));
Your code doesn't compile. Don't try to execute non-compiling code. Fix all the compilation errors before executing the code. They're visible in the "Problems" view of your Eclipse IDE.
You need to call Grades.getSum and Grades.getAverage to get the right result. Also, don't forget to import the Grade class, using the command import Grades; in the beginning of the UserInteraction class.
I'm starting my first steps with 2D arrays in Java. I require some help on a practical example. The below code should store students and their results for the 3 different courses in a table but the code throws an error. The error is caused by the line int studentResults[x][y] = sc.nextInt(); Any ideas? Thanks.
import java.util.*;
class CalcAverage
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("how many students?: ");
int nbrOfStudents = sc.nextInt();
int[][] studentResults ;
studentResults = new int[nbrOfStudents][3] ;
for (int x = 0 ; x < nbrOfStudents ; x++)
{
System.out.println("Student " + (x + 1) + " : ");
for (int y =0 ; y < 3 ; y++)
{
System.out.println("enter result course " + (y + 1) + " : ");
int studentResults[x][y] = sc.nextInt();
}
}
}// end main
}//end class
Just say studentResults[x][y] = sc.nextInt(); with no int in front of it.
You only put the type in front of a variable name when you are first declaring it.