I am creating a Premier League football table in my spare time and I have come across a problem. While the program runs I want it to be perfect and output in the format I want it to, the problem is:
You enter the the Input (" HomeTeam : AwayTeam : HomeScore : AwayScore ") as follows
When you are done with the list you enter "quit" to stop the program
My issue is that the scores come out like this
(" HomeTeam | AwayTeam | HomeScore | AwayScore ")
I intend it to print like this (" HomeTeam [HomeScore] | AwayTeam [AwayScore] ")
I have tried many variations of System.out.printlns to no avail, even trying to make several Boolean conditions that will output the input in the way I want it too. I am truly at a loss and it is frustrating - I hope that someone can give me tips the code is attached
Edited for loop;
for (int i = 0; i < counter; i++) { // A loop
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + "[" + words[2].trim() + "]" + " | " + words[1].trim() + "[" + words[3].trim()) + "]";
This should work:
Scanner sc = new Scanner(System.in);
public void outputScore(String input) {
String[] words = input.trim().split("\\s+");
String satisfied = sc.nextLine();
if (satisfied.equals("quit")) {
System.out.println(words[0] + " [" + words[4] + "] | " + words[2] + " [" + words[6] + "]");
}
}
This is what the method should look like when you call it:
outputScore(sc.nextLine());
Here is the code to your edited question:
String [] product_list = new String [100];
int counter = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Input as follows:");
System.out.println("Home team : Away team : Home score : Away score");
String line = null;
while (!(line = scanner.nextLine()).equals("")) {
if (line.equals("quit")) {
break;
} else {
product_list[counter] = line;
System.out.println("Home team : Away team : Home score : Away score");
}
counter++;
}
for (int i = 0; i < counter; i++) {
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + " : " + words[2].trim() + " | " + words[1].trim() + " : " + words[3].trim());
}
Hope this helps.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
I am having an issue that I cannot get rid off.
I am running the code from bellow and for this input:
*Enter cells: XXOO_OX
| X X |
| O O |
| O X |
Enter the coordinates:You should enter numbers!
Enter the coordinates:one
You should enter numbers!
Enter the coordinates:ont three
You should enter numbers!
Enter the coordinates:1 3
| X X X |
| O O |
| O X |
Process finished with exit code 0*
and after running it I get the catch message before I input the coordinates. Why? What should I change?
Scanner scanner = new Scanner(System.in);
String[][] tictactoe = new String[3][3];
//init method
System.out.print("Enter cells: ");
String s = scanner.next();
String a = s.substring(0, 1);
tictactoe[0][0] = a;
String b = s.substring(1, 2);
tictactoe[0][1] = b;
String c = s.substring(2, 3);
tictactoe[0][2] = c;
String d = s.substring(3, 4);
tictactoe[1][0] = d;
String e = s.substring(4, 5);
tictactoe[1][1] = e;
String f = s.substring(5, 6);
tictactoe[1][2] = f;
String g = s.substring(6, 7);
tictactoe[2][0] = g;
String h = s.substring(7, 8);
tictactoe[2][1] = h;
String i = s.substring(8, 9);
tictactoe[2][2] = i;
for (int n = 0; n < 3; n++) {
for (int m = 0; m < 3; m++) {
String cuv = tictactoe[n][m];
if (cuv.equals("_")) {
tictactoe[n][m] =" ";
}
}
}
System.out.println("---------");
System.out.println("| " + tictactoe[0][0] + " " + tictactoe[0][1] + " " + tictactoe[0][2] + " |");
System.out.println("| " + tictactoe[1][0] + " " + tictactoe[1][1] + " " + tictactoe[1][2] + " |");
System.out.println("| " + tictactoe[2][0] + " " + tictactoe[2][1] + " " + tictactoe[2][2] + " |");
System.out.println("---------");
String player1 = "X";
String letter;
boolean correctCoordinate=false;
while (!correctCoordinate){
System.out.print("Enter the coordinates:");
String input=scanner.nextLine();
String [] pieces = input.trim().split("\\s+");
int x;
int y;
try {
x = Integer.parseInt(pieces[0]);
y = Integer.parseInt(pieces[1]);
letter = tictactoe[3-y][x-1];
if (letter.equals("X") || letter.equals("O")) {
System.out.println("This cell is occupied! Choose another one!");
} else {
tictactoe[3-y][x-1]=player1;
System.out.println("---------");
System.out.println("| " + tictactoe[0][0] + " " + tictactoe[0][1] + " " + tictactoe[0][2] + " |");
System.out.println("| " + tictactoe[1][0] + " " + tictactoe[1][1] + " " + tictactoe[1][2] + " |");
System.out.println("| " + tictactoe[2][0] + " " + tictactoe[2][1] + " " + tictactoe[2][2] + " |");
System.out.println("---------");
correctCoordinate=true;
}
}catch (NumberFormatException err1) {
System.out.println("You should enter numbers!");
}catch (ArrayIndexOutOfBoundsException err2){
System.out.println("Coordinates should be from 1 to 3!");
}
}
Thank you,
Florin
The best way to debug your code is by stack tracing.
Try adding
catch (NumberFormatException err1) {
err1.printStackTrace();
System.out.println("You should enter numbers!");
}catch (ArrayIndexOutOfBoundsException err2){
err2.printStackTrace();
System.out.println("Coordinates should be from 1 to 3!");
}
This way you can trace your issue.
Hope it was helpful.
Have a nice day :)
I have a working code but my output doesn't count up.
Here is the code I am working with:
for(Course course : courses) {
for(int i=0;i<1;i++) {
System.out.println("[" + (i+1) + "]" + course.getCode() + "(" + course.getCreditHour() + ")");
}
}
System.out.print("Enter your choice : ");
I need the (i+1) to count from one to 7.
Here is a copy of the output I currently get:
Please type the number inside the [] to register for a course
The number inside the () is the credit hours for the course
[1]IT1006(6)
[1]IT4782(3)
[1]IT4789(3)
[1]IT4079(6)
[1]IT2230(3)
[1]IT3345(3)
[1]IT2249(6)
Enter your choice :
I need the numbers inside the square brackets to count from 1 to 7.
This is for an academic assignment.
Your inner loop isn't doing anything. There's no point in using a loop if you've hard coded it to just run once.
I'd get rid of your outer loop and just index courses directly:
for(int i = 0; i < courses.size(); i++){
Course course = courses.get(i);
System.out.println("[" + (i+1) + "]" + course.getCode() + "(" + course.getCreditHour() + ")");
}
for(Course course : courses) means : for each course so i is reinitialised you whant a variable that will be increment on each iteration so the variable must be declared outside the block. you can write some thing like this :
int i = 1;
for(Course course : courses) {
System.out.println("[" + (i++) + "]" + course.getCode() + "(" + course.getCreditHour() + ")");
}
System.out.print("Enter your choice : ");
the method of #Carcigenicate will work too but can handle so performance issue if you use linked structure as linkedlist tthis will become for an Array :
for (int i = 0 ; i < courses.lenght ; i++){
System.out.println("[" + i + "]" + courses[i].getCode() + "(" + courses[i].getCreditHour() + ")");
}
System.out.print("Enter your choice : ");
and on collections :
for (int i = 0 ; i < courses.getSize(); i++){
System.out.println("[" + i + "]" + courses.get(i).getCode() + "(" + courses.get(i).getCreditHour() + ")");
}
System.out.print("Enter your choice : ");
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I keep getting an error when trying to delete or display the users that I've created. Pointing to the line of code where it actually does the deletion or displaying of a certain user. I can't seem to figure out where the error is coming from.
import java.util.*;
public class contactInfo {
public static void main(String[] args) {
String tracker[][] = {
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",}
};
Scanner input = new Scanner(System.in);
int picker = 0;
while (true) {
System.out.print("Please choose an option: \n 1. Add a user \n 2. Delete a user \n 3. Display a user \n 4. Quit ");
picker = input.nextInt();
if (picker == 1) {
addUser(tracker);
} else if (picker == 2) {
deleteUser(tracker);
} else if (picker == 3) {
displayUser(tracker);
} else {
break;
}
}
}
public static String[][] addUser(String[][] add) {
Scanner input = new Scanner(System.in);
System.out.print("Which user is this information for (1 - 10): ");
int user = input.nextInt();
System.out.println(" ");
System.out.print("Enter the users first name: ");
add[user][0] = input.next();
System.out.println(" ");
System.out.print("Enter the users last name: ");
add[user][1] = input.next();
System.out.println(" ");
System.out.print("Enter the users phone number (without dashes): ");
add[user][2] = input.next();
System.out.println(" ");
System.out.print("Enter the users age: ");
add[user][3] = input.next();
System.out.println(" ");
return add;
}
public static String[][] deleteUser(String[][] del) {
Scanner input = new Scanner(System.in);
System.out.print("Which user would you like to delete?: ");
int user = input.nextInt();
for (int i = 0; i < del.length - 1; i++) {
del[user][i] = " ";
}
return del;
}
public static String[][] displayUser(String[][] displ) {
Scanner input = new Scanner(System.in);
System.out.print("Which user would you like to display?: ");
int user = input.nextInt();
for (int i = 0; i < displ.length; i++) {
System.out.print(displ[user][i] + " ");
}
return displ;
}
}
Your tracker is a 2-dimensional array. 10 rows of 4 strings each. The problem is this code:
for (int i = 0; i < del.length - 1; i++)
{
del[user][i] = " ";
}
You iterate over the array of 4 strings, but the variable i will go from 0 to 8. What you want is something like:
for (int i = 0; i < del[user].length; i++)
{
del[user][i] = " ";
}
Instead of using displ.length or del.length for you limits, use displ[user].length or del[user].length.
Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}
Snippet of my code:
...
System.out.println("\t" + "MONTH |" + "\t" + "HIGH | " + "\t" + "LOW |" + "\t" + "AVERAGE |" + "\t" + "RANGE");
System.out.println("\t" + "______________________________________________");
main.averageMonthOne(hightemp, lowtemp);
in1.close();
out.close();
}//end of main
private static double averageMonthOne (int hightemp, int lowtemp)
{
double avgM = (hightemp + lowtemp)/2;
System.out.println(avgM);
return avgM;
}
I want to be able to use the average I received from averageMonthOne and place it respectively under a the word "AVERAGE" in the println. Is that possible?
Expected Output:
MONTH | HIGH | LOW | AVERAGE | RANGE
_____________________________________
30.0
Use System.out.printf() and format accordingly !
Very possible Just change your code to be like the following:
...
System.out.println("\t" + "MONTH |" + "\t" + "HIGH | " + "\t" + "LOW |" + "\t" + "AVERAGE |" + "\t" + "RANGE");
System.out.println("\t" + "______________________________________________");
double myresult = main.averageMonthOne(hightemp, lowtemp);
System.out.println("\t\t\t\t" + myresult);
in1.close();
out.close();
}//end of main
private static double averageMonthOne (int hightemp, int lowtemp)
{
double avgM = (hightemp + lowtemp)/2;
System.out.println(avgM);
return avgM;
}
This works, if you have a fixed number of Strings, that can be filled or empty. Have a bunch of variables ready like this:
String avg = "", high = "", low = "", ...;
Next, fill those you need with values:
avg = averageMonthOne(hightemp, lowtemp);
high = ...;
low = ...;
Lastly, call the String.format method to gather it all up:
String s = String.format("%s %s %s", avg, high, low);
System.out.println(s);
You could shorten the above to
System.out.format("%s %s %s", avg, high, low);
According to http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html, there are lots of options for formatting and spacing the output, just change the first argument of the format method accordingly.
If I where you I would create an Array of Strings where you put the numbers you get. For example:
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader("fileName.txt"));
String[] numbers = new String[5];
for(int i=0; i<5; i++){ // here you only read 5 values from a file, line by line. If the file is formatted differently you have to read them differently.
numbers[i] = bufferedReader.readLine();
}
}catch(IOException io){ ... }
Then you format the array of strings into one single String line like this:
String printedNumbers = "";
for(int i=0; i<numbers; i++){
printNumbers+="\t"; // every table cell is seperated by a TAB
if(numbers[i] == null){ // if the cell is empty
printNumbers +=\t; // fill it with a TAB
}else{
printNumbers +=numbers[i]; // otherwise put the number in
}
}
This may be a little much for only 5 values, but you shouldn't have to fill the gaps between your "table cells" with whitspaces. In the end to print your table do:
System.out.println("\t" + "MONTH |" + "\t" + "HIGH | " + "\t" + "LOW |" + "\t" + "AVERAGE |" + "\t" + "RANGE");
System.out.println("\t" + "______________________________________________");
System.out.println(printNumbers);