This program gets user input for 2 teams and 2 results, separates them with the " : " delimiter, then stores them in the array, when the user enters the word "stop" it stops asking for user input and is meant to display the results and stats of the match (which is not yet added into the code). the problem I'm having is if I type more than one line of match results then type 'stop', it only displays the first line of user input back to the console and not any of the others? input example: "Chelsea : Arsenal : 2 : 1".
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
if ("stop".equals(line)) {
System.out.println(Arrays.toString(results));
return; // exit
}
The reason that it outputs the first results you entered is because results is assigned to s.split(" : "). s never changes in the first iteration of the outer for loop, so s.split(" : ") never changes. Your results always holds the first match results!
You have written your code very wrongly.
First, why do you have a while loop inside a for loop? The for loop is redundant.
Second, you can't use arrays for this. Try an ArrayList. Arrays don't have the ability to change its size dynamically.
Third, I recommend you to create a class for this, to represent a MatchResult.
class MatchResult {
private String homeTeam;
private String awayTeam;
private int homeScore;
private int awayScore;
public String getHomeTeam() {
return homeTeam;
}
public String getAwayTeam() {
return awayTeam;
}
public int getHomeScore() {
return homeScore;
}
public int getAwayScore() {
return awayScore;
}
public MatchResult(String homeTeam, String awayTeam, int homeScore, int awayScore) {
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.homeScore = homeScore;
this.awayScore = awayScore;
}
#Override
public String toString() {
return "MatchResult{" +
"homeTeam='" + homeTeam + '\'' +
", awayTeam='" + awayTeam + '\'' +
", homeScore=" + homeScore +
", awayScore=" + awayScore +
'}';
}
}
Then, you can create an ArrayList<MatchResult> that stores the user input.
Scanner sc = new Scanner(System.in);
String hometeam;
String awayteam;
int homescore;
int awayscore;
ArrayList<MatchResult> list = new ArrayList<>();
System.out.println("please enter match results:");
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(list.toArray()));
return; // exit
}
String results[] = line.split(" : "); // parse strings in between
hometeam = results[0];
awayteam = results[1];
homescore = Integer.valueOf(results[2]);
awayscore = Integer.valueOf(results[3]);
list.add(new MatchResult(hometeam, awayteam, homescore, awayscore));
}
try just adding another array
string[] matches = new string[]{};
then input your values into the array. I am using b since that is the int variable in your loop. I also put in + " : "
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
then change the print to
System.out.println(Arrays.toString(matches));
i think this should work, but I wasn't able to test it.
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
string[] matches = new string[]{};
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(matches));
return; // exit
}
Here is a simple loop to grab all data from user until "stop" is entered and display the output of the input
Scanner sc = new Scanner(System.in);
ArrayList<String[]> stats = new ArrayList<>(); //initialize a container to hold all the stats
System.out.println("please enter match results:");
while(sc.hasNextLine())
{
String input = sc.nextLine();
String[] results = input.split(" : ");
if(results.length == 4)
{
stats.add(results);
}
else if(input.equals("stop"))
break;
else
System.out.println("Error reading input");
}//end of while
for(int i = 0; i < stats.size(); i++)
{
try{
System.out.println(stats.get(i)[0] + " vs " + stats.get(i)[1] + " : " +
Integer.valueOf(stats.get(i)[2]) + " - " + Integer.valueOf(stats.get(i)[3]));
}catch (Exception e) {
//do nothing with any invalid input
}
}
Output
please enter match results:
r : b : 5 : 4
r : c : 7 : 10
j : g : 3 : 9
stop
r vs b : 5 - 4
r vs c : 7 - 10
j vs g : 3 - 9
Related
public static void main(String[] args) {
i got to enter the amount of names i want, then input them by scanner in console, and after print the longest one, it's mostly done, but i want to print it by JoptionPane aswell
Scanner wczytanie = new Scanner(System.in);
System.out.println("ENTER THE AMOUNT OF NAMES");
int size = wczytanie.nextInt();
String[] array = new String[size];
System.out.println("ENTER THE NAMES");
String name = wczytanie.nextLine();
for (int i = 0; i < array.length; i++) {
array[i] = wczytanie.nextLine();
if (name.length() < array[i].length()) {
name = array[i];
}
}
// System.out.println("LONGEST NAME: " + name);
String name1 = new String();
if(name == name1) {
JOptionPane.showMessageDialog(null, " THE LONGEST NAME IS " + name1);
}
}
You have a lot of problems here: you're reading from the scanner before the loop when reading names and you're doing a raw object equality on a new string for some reason that will never work. You want something more like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("How many names? ");
int num = scanner.nextInt();
List<String> names = new ArrayList<>(num);
System.out.println("Enter names: ");
for (int i = 0; i < num; i++) {
names.add(scanner.next());
}
String longest = names.stream().reduce((a, b) -> a.length() > b.length() ? a : b).get();
System.out.println("The longest name is: " + longest);
JOptionPane.showMessageDialog(null, "The longest name is: " + longest);
}
}
I'm a beginner in Java. I have an assignment that require me to take 3 input from user, then output the 3 at the same time.
here is my code. i have only get 1 output.
suppose look like this:
anyone could help, thx!
here is my code
Scanner sc = new Scanner(System.in);
int i = 0;
String classname = " ";
String rating = " ";
int plus = 0;
while(i < 3){
System.out.print("What class are you rating? ");
classname = sc.nextLine();
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus = Integer.parseInt(rating);
i++;
}
System.out.print(classname + ": ");
while (plus > 0){
System.out.print("+");
plus --;
}
System.out.println();
The very first thing I would do is create a Course POJO (Plain Old Java Object). It should have two fields, name and rating. And I would implement the display logic with a toString in that Course POJO. Like,
public class Course {
private String name;
private int rating;
public Course(String name, int rating) {
this.name = name;
this.rating = rating;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rating; i++) {
sb.append("+");
}
return String.format("%s: %s", name, sb);
}
}
Then your main method simply involves filling a single array of three Course instances in one loop, and displaying them in a second loop. Like,
Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
System.out.print("What class are you rating? ");
String className = sc.nextLine();
System.out.printf("How many plus signs does %s get? ", className);
int classRating = Integer.parseInt(sc.nextLine());
courses[i] = new Course(className, classRating);
i++;
}
i = 0;
while (i < courses.length) {
System.out.println(courses[i]);
i++;
}
You overwrite your variables classname and rating in each loop. You need to store each iteration in a field of an array.
Scanner sc = new Scanner(System.in);
int i = 0;
String[] classname = new String[3]; //create array
String rating = " "; //rating can be overwritten, it is not needed after the loop
int[] plus = new int[3];
while(i < 3){
System.out.print("What class are you rating? ");
classname[i] = sc.nextLine(); //name[index] to read/write fields of an array
//index starts at 0
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus[i] = Integer.parseInt(rating);
i++;
}
for(i = 0;i<3;i++){ //iterate over all elements in the array
System.out.print(classname[i] + ": ");
while (plus[i] > 0){
System.out.print("+");
plus[i] --;
}
System.out.println();
}
I am writing a program that searches a file imported for a string of characters and length user enters. For example,
"Enter the possible letters in your word: "
Keyboard scans "aeppr"
"Enter the number of letters in your target words:"
"5"
and then proceeds to search my dictionary file and ultimately prints:
1 paper
I was wondering if you can use indexOf or any other methods or classes to display this result. As of now my code only displays words that match the searched letters and length exactly. Any help or advice would be greatly appreciated.
String input;
String altInput;
Scanner inFile = new Scanner(new File("words.txt"));
Scanner scanner = new Scanner(System.in);
String lettersBeingTested;
int numberOfLetters;
System.out.println("Enter the possible letters in your word: ");
lettersBeingTested = scanner.next();
System.out.println("Enter the number of letters in your target words: ");
numberOfLetters = scanner.nextInt();
int count = 0;
while (inFile.hasNext()) {
input = inFile.next();
altInput = "";
for (int i = 0; i < input.length(); i++) {
altInput = altInput + input.charAt(i);
if (input.contains(lettersBeingTested) && altInput.length() == numberOfLetters) {
count++;
System.out.println(count + " " + altInput);
}
}
}
System.out.println("End of list: " + count + " words found");
inFile.close();
}
public static void main(String[] args) throws FileNotFoundException {
findWords(new File("words.txt"));
}
public static void findWords(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter the possible letters in your word: ");
String lettersBeingTested = scan.next();
System.out.println("Enter the number of letters in your target words: ");
int numberOfLetters = scan.nextInt();
int[] requiredHistogram = histogram(lettersBeingTested, new int[26]);
Predicate<int[]> predicate = wordHistogram -> {
for (int i = 0; i < requiredHistogram.length; i++)
if (requiredHistogram[i] > 0 && wordHistogram[i] < requiredHistogram[i])
return false;
return true;
};
Set<String> words = findWords(file, predicate, numberOfLetters);
int i = 1;
for (String word : words)
System.out.println(i + " " + word);
System.out.println("End of list: " + words.size() + " words found");
}
}
private static int[] histogram(String str, int[] histogram) {
Arrays.fill(histogram, 0);
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++)
histogram[str.charAt(i) - 'a']++;
return histogram;
}
private static Set<String> findWords(File file, Predicate<int[]> predicate, int numberOfLetters) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
Set<String> words = new LinkedHashSet<>();
int[] histogram = new int[26];
while (scan.hasNext()) {
String word = scan.next().toLowerCase();
if (word.length() == numberOfLetters && predicate.test(histogram(word, histogram)))
words.add(word);
}
return words;
}
}
This look a bit complicated using histogramm. I think that if lettersBeingTested = "aa", then you're looking for words with at lest 2 'a' in it. Threfore, you have to build a histogram and compare symbol appearance number in the current words and in example one.
P.S.
altInput = altInput + input.charAt(i);
String concatenation within loop flows bad performance. Do look at StringBuilder isntead.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I cannot figure out how to delete a student in my student array. I need to continue the array with no gaps or breaks and i am having some trouble doing that. I am also having issues setting the information into the array when adding a student. I can ask for the information but saving it to the array I cant figure out.
import java.util.Scanner;
public class ArrayDemo
{
static Student[] students;
private static void ViewStudents()
{
for( int i = 0; i < students.length; i++)
{
System.out.println( i + ") " + students[i].getLName() + ", " + students[i].getFName() );
}
}
private static void ViewDetails()
{
Scanner kb = new Scanner( System.in );
int i;
System.out.println( "Who would you like to view?");ViewStudents();
i = Integer.parseInt( kb.nextLine() );
System.out.println( "ANum:\t\t" + students[i].getANum() );
System.out.println( "\nAddress:\t" + students[i].address.getHouseNum() + " " + students[i].address.getStreet());
System.out.println( "\t\t" + students[i].address.getCity() + ", " + students[i].address.getState() + " " + students[i].address.getZip());
System.out.println( "\t\t" + students[i].address.getLine2());
}
private static void AddStudent()
{
Scanner kb = new Scanner( System.in );
Student student = new Student();
String FirstName;
String LastName;
int HouseNum ;
String Street;
String City ;
String State ;
int Zip ;
String Line2 ;
/* System.out.println( "\tFirst:" + student.getFName() + "\n\tLast:" + student.getLName() + "\n\tA-Number:" +student.getANum()); */
System.out.println( "\tInput Information" );
System.out.println( "\tFirst Name:");
FirstName = kb.nextLine();
System.out.println( "\tLast Name:");
LastName = kb.nextLine();
System.out.println( "\tHouse Number:");
HouseNum = Integer.parseInt( kb.nextLine() );
System.out.println( "\tStreet:");
Street = kb.nextLine();
System.out.println( "\tCity:");
City = kb.nextLine();
System.out.println( "\tState:");
State = kb.nextLine();
System.out.println( "\tZip Code:");
Zip = Integer.parseInt( kb.nextLine() );
System.out.println( "\tExtra Information:");
Line2 = kb.nextLine();
System.out.println( "\nStudent:\t" + LastName + ", " + FirstName );
System.out.println( "ANum:\t\t" + student.getANum() );
System.out.println( "Address:\t" + HouseNum + " " +Street);
System.out.println( "\t\t" + City + ", " + State + " " + Zip);
System.out.println( "\t\t" + Line2);
//students.setAddress( HouseNum, Street, City, State, Zip, Line2 );
System.out.println( "\tYour Student was Successfully Added" );
}
private static void RemoveStudent()
{
Scanner kb = new Scanner( System.in );
int i;
System.out.println( "Who would you like to remove?");ViewStudents();
i = Integer.parseInt( kb.nextLine() );
for( i < student.length - 1; i++)
{ students[i] = students[i + 1];
students[students.length - 1] = null;
}
public static void main( String[] args )
{
Scanner kb = new Scanner( System.in );
int x = 40;
//students = new Student[0];
students = new Student[2];
students[0] = new Student( "Thomas","Emily");
students[1] = new Student( "Bob", "Joe");
students[0].address = new Address( 6614, "White Sands ln", "Hixson", "Tennessee", 37343, "" );
students[1].address = new Address( 66, "White ln", "Hson", "Tealamabaee", 373873, "" );
do
{
System.out.println();
System.out.println( "Do you want to:" );
System.out.println( "\t0) View Students" );
System.out.println( "\t1) View Students' Details" );
System.out.println( "\t2) Add a Student" );
System.out.println( "\t3) Remove a Student" );
System.out.println( "\t4) Exit" );
x = Integer.parseInt(kb.nextLine());
switch (x)
{
case 0:
ViewStudents();
break;
case 1:
ViewDetails();
break;
case 2:
AddStudent();
break;
case 3:
RemoveStudent();
break;
case 4:
break;
default:
}
}
while( x != 4);
}
}
Student.java
import java.util.Random;
public class Student
{
Address address; //javac will now compile Address.java
// List private data first -- it's polite to my programmer-user.
private String LName; // Last Name
private String FName; // First Name
private int ANum; // A number
public Student()
{
Random rand = new Random();
LName = "";
FName = "";
// ANum = 0;
ANum = rand.nextInt( 99999999 );
}
public Student( String ln, String fn/*, int an*/ )
{
Random rand = new Random();
LName = ln;
FName = fn;
// ANum = an;
ANum = rand.nextInt( 99999999 );
}
public boolean setLName( String ln )
{
LName = ln;
return true;
}
public String getLName()
{
return LName;
}
public boolean setFName( String fn )
{
FName = fn;
return true;
}
public String getFName()
{
return FName;
}
// public boolean setANum( int an )
// {
// ANum = an;
// return true;
// }
public String getANum()
{
// String str = String.format( "A%08d", ANum );
// return "A" + ANum;
// return str;
return String.format( "A%08d", ANum );
}
}
When I see the word student, it appears to me that this is a school work. Thus, I wouldn't ask you to use anything more than array.
To delete a record in an array:
In array, if you want to delete a record with no gaps in-between, you have to "shift up" the records behind one by one. This is the only way to close a gap in array. (without using any other data structures).
//record of student, index to be deleted, number of records you have
public static int deleteRecord(Student[] record, int idx, int numOfRecords)
{
if(idx < 0 || idx > numOfRecords) //Check index is valid
return -1;
for(int x=idx; x<numOfRecords; x++) //closing the gap by copying the next value
record[x] = record[x+1];
return (--numOfRecords);
}
To add a record in an array:
Check whether the limit for number of records has been reached.
If still have space for more, add at the last available slot.
Adding a student record:
public static int addRecord(Student[] record, int numOfRecords)
{
if(numOfRecords >= record.legnth) //Check record is not full yet
return -1;
//prompt for student particulars
record[numOfRecords].name = xxx; //where xxx is input by user
record[numOfRecords].id = yyy; //where yyy is input by user
return (++numOfRecords);
}
I've seen many university/college having this kind of assignment. They normally expect you to keep track of the number of records you currently have.
Because you didn't post how your Student class looks like. If you have a static variable in Class Student recording the number of students objects added. You don't have to manually keep track of number of records. It will look like this if you have a counter in your Student class:
public class Student
{
static int numOfRecords = 0;
public Student()
{
numOfRecords++;
}
}
To maintain what you currently have, add one more static variable outside your main. (It looks like your don't want to pass anything to the methods)
static int numOfRecords = 0; //declare outside your main
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[numOfRecords] = stud;
numOfRecords ++;
}
That's all you need to add.
ArrayList<E> is your friend here. With this, you can add and remove elements, with the gaps filling up automatically. Need import java.util.ArrayList<E>;
ArrayList<Student> = new ArrayList();
Ensures a size of 10, which can be accessed with the size() method. add(E e) will allow you to append to the list, and remove(Object o) or remove(int i) lets you remove either a specific index or a specific instance of type E.
Alternatively, shifting everything away could do the trick
Given an array of type Foo, say you want to remove the object at index 3.
for(int i = 3; i < arr.length - 1; i++)
arr[i] = arr[i + 1];
arr[arr.length - 1] = null;
To add an object(still an array of type foo),
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
arr[i] = bar;
break;
}
}
import java.util.Arrays;
public class Test
{
static Student[] students = new Student[3];
public static void main (String[] args) {
students[0] = new Student ("Thomas");
students[1] = new Student ("Bob");
students[2] = new Student ("Mark");
removeStudent(1);
for (Student s : students) {
System.out.println(s.getName());
}
}
public static void removeStudent (int index) {
// valid index
if (index < 0 || index > students.length) {
return;
}
// null it
students[index] = null;
// move all elements after index back
for (int i = index; i < students.length-1; i++) {
students[index] = students[index+1];
}
Student[] temp = Arrays.copyOf(students, students.length-1);
students = temp;
}
}
This is a simplified version of your code. Student now only has a name with a getter for it. But that removeStudent reallocates the memory for students.
Hope you can draw some wisdom from it.
Okay so I have to write a program that loops and continues to ask for a pair of numbers until the user enters -1 in which case the program terminates. The combination numbers will be written like this : " 10 2" Without the quotes. When I type it in I get an error any idea what is wrong with my code?
Here is my code:
import java.util.*;
public class Combinations
{
public static int combinations( int n, int p )
{
if ( p == 0 )
return 1;
else if ( n == p )
return 1;
else
return ( combinations( n - 1, p - 1 ) + combinations( n - 1, p ) );
}
public static void main(String [] args)
{
int a=0;
int b=0;
boolean end = false;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the combination numbers");
while (end==false)
{
String line = scan.next();
StringTokenizer str=new StringTokenizer(line, " ");
String st = str.nextToken();
a = Integer.parseInt(st);
String st1 = str.nextToken();
b = Integer.parseInt(st1);
if(a==-1||b==-1)
{
end=true;
}
System.out.println(combinations(a,b));
}
}
}
Rather than using a StringTokenizer try
String line = scan.nextLine(); // not next
String str[] = line.split (" ");
// check that str.length is 2
String st = str[0];
a = Integer.parseInt(st);
String st1 = str[1];
b = Integer.parseInt(st1);
if(a==-1||b==-1)
{
break;
}
To get the full line use 'nextLine()' then tokenize it.
String line = scan.nextLine();
use this ...
String line = scan.nextLine();
instead of
String line = scan.next();
because its not take value after space.......