Part of my java code is not running. I am fairly new to java and have been working out some new environment changes. My class was told to build a windchill temperature calculator. My main issue is that my code works up to the for (ws = wsp; ws <= c; ws += 0.5) then stops.
import java.util.*;
class Assign1
{
public static void main(String args[])
{
Menu user = new Menu();
Menu.mainmenu();
user.acceptSelection();
}
}
class Menu
{
public static void mainmenu()
{
System.out.println("Temperature Analysis MENU");
System.out.println("1.W)ind Chill Temperature");
System.out.println("0.E)xit");
System.out.println("Enter Selection:");
}
public void acceptSelection()
{
Scanner stdin = new Scanner(System.in);
String selection = stdin.nextLine();
char choice = selection.charAt(0);
switch(choice)
{
case 'W':
case 'w':
case '1':
processing.process(); break;
case 'E':
case 'e':
case '0':
System.out.println("E"); break;
}
}
}
class processing
{
public static void process()
{
Scanner stdin = new Scanner(System.in);
System.out.println("\n\n\n\n\n\n\n");
System.out.print("Please enter START air temp in celsius (decimal) MUST be BELOW 9: ");
double sa = stdin.nextDouble();
System.out.print("Please enter END air temp in celsius (decimal) MUST be BELOW 9: ");
double ea = stdin.nextDouble();
System.out.print("Please enter wind speed (decimal) FROM 8km/h to: ");
double w = stdin.nextDouble();
System.out.println("\n==================================================================\n");
calculation(sa, ea, w);
}
public static void calculation(double a, double b, double c)
{
double wsp = 8.0;
double airTemp;
double ws;
int size = 150;
double[] wChill = new double[size];
int count = 0;
System.out.print(" " + a);
while(a <= b)
{
System.out.print(" " + a);
a +=5;
count++;
}
System.out.print(" " + b);
int count2 = 0;
while(wsp <= c)
{
count2++;
wsp += 0.5;
}
double[][] chart = new double[count2][count];
int i = 0, j = 0, k = 0;
This is where it stops working. I cannot get it to print my loop out. Any help in fixing my problem would be appreciated as well as notes to my code as i am trying to improve. I am using JGrasp if it helps.
for (ws = wsp; ws <= c; ws += 0.5)
{
System.out.println(ws + " ");
for (airTemp = a; airTemp <= b; airTemp += 5.0)
{
if ((ws + 0.5) > c)
{
System.out.printf( "%2d %2d", c , chart[k][i]);
}
else
{
wChill[i] = (13.12 + (0.6215*airTemp)+(-11.37*Math.pow(ws, 0.16))+(0.3965*airTemp*Math.pow(ws, 0.16)));
chart[k][i] = wChill[i];
System.out.print(chart[k][i] + " ");
}
i++;
}
k++;
}
}
}
According to you code you have a while loop
while(wsp <= c) {...}
then you have a for loop
for (ws = wsp; ws <= c; ws += 0.5)
so as you can see ws is assigned the value of wsp which has in the while already exceeded the value of c
Related
I am making a program which allows the user to look at student's grades, find the average, find the highest grade, the lowest etc. For one of the methods I have, it checks for the average of the values that the user entered. I tried to do this but to no avail. Here is the specific code:
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
For some better context, here is the rest of the code:
import java.util.Scanner;
public class StudentGradeArray {
static Scanner input = new Scanner(System.in);
static String[] studentName;
static String letterGrade = " ";
static int[] studentGrade;
static int gradeMax = 0;
static int gradeMin = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("How many students are you entering into the database?");
int numOfKids = input.nextInt();
studentGrade = new int[numOfKids];
studentName = new String[numOfKids];
for (int i = 0; i < numOfKids; i++) {
System.out.println("Enter the student's name:");
studentName[i] = input.next();
System.out.println("Enter " + studentName[i] + "'s grade");
studentGrade[i] = input.nextInt();
}
do {
System.out.println("");
System.out.println("Enter a number for the following options:");
System.out.println("");
System.out.println("1. Student's letter grade");
System.out.println("2. Search for a student and their grade");
System.out.println("3. The class average");
System.out.println("4. The student with the highest grade");
System.out.println("5. The student with the lowest grade");
System.out.println("6. List of students that are failing");
System.out.println("7. Quit the program");
int options = input.nextInt();
switch(options) {
case 1:
letterGrade(options); break;
case 2:
searchStudent(); break;
case 3:
classAvg(options); break;
case 4:
markHighest(options); break;
case 5:
markLowest(options); break;
case 6:
markFailing(options); break;
case 7:
return;
default:
System.out.println("");
System.out.println("Please enter a valid option.");
System.out.println(""); break;
}
} while (!input.equals(7));
System.out.println("Program Terminated.");
}
public static void letterGrade(int numOfKids) {
System.out.println("Enter a grade: A, B, C, D, F");
letterGrade = input.next();
if (letterGrade.equalsIgnoreCase("a")) {
gradeMax = 100;
gradeMin = 80;
}
if (letterGrade.equalsIgnoreCase("b")) {
gradeMax = 79;
gradeMin = 70;
}
if (letterGrade.equalsIgnoreCase("c")) {
gradeMax = 69;
gradeMin = 60;
}
if (letterGrade.equalsIgnoreCase("d")) {
gradeMax = 59;
gradeMin = 50;
}
if (letterGrade.equalsIgnoreCase("f")) {
gradeMax = 49;
gradeMin = 0;
}
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] <= gradeMax && studentGrade[i] >= gradeMin) {
System.out.println(studentName[i] + " has a " + letterGrade);
System.out.println(letterGrade + " is equivalent to " + gradeMin + " - " + gradeMax + "%");
}
}
}
public static void searchStudent() {
}
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
public static void markHighest(int numOfKids) {
int highestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] > highestNum) {
highestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + highestNum + "%");
}
public static void markLowest(int numOfKids) {
int lowestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < lowestNum) {
lowestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + lowestNum + "%");
}
public static void markFailing(int numOfKids) {
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < 50) {
System.out.println(studentName[i] + " is failing with a mark of " + studentGrade[i] + "%");
}
}
}
}
Looks like the argument passed to the classAvg() is not the numOfKids (or size of array) but the option selected by the user from the menu. Trying passing 'numOfKids' instead of passing 'options' as an argument to the function
case 3:
classAvg(options); break;
Better still use studentGrade.length instead of passing argument.
case 3:
classAvg(options); break;
You are passing in the options, but the method wants numOfKids. In this case options will always be 3.
Try passing in numOfKids instead.
Another problem I see is that both average and numOfKids are integers, which causes chopping remainders and rounding to 0 if the denominator is greater. Perhaps change from
average = (average/numOfKids) * 100;
to
average = ((double) average)/ numOfKids * 100;
I think it is better to create a class called Student, with properties name and grade. for more OOP design.
public class Student{
int[] grades;
String name;
public Student(int[] grade, String name){
this.grade = grade;
this.name = name;
}
public double getAverage(){
return (average/(double)numOfKids) * 100;
}
...
}
And average is of type int and numOfKids too, so the division is not gonna be precise. try this average = (average/(double)numOfKids) * 100;
I'm really new to Java and I'm having issues with a program required for my Java class. I need to simulate a lock and implement methods that change combination, check the number on top etc.
Well, I think there's an issue with my openLock() method or alterLockCombination() method. My program will correctly open the lock with default combination (0,0,0) but when I try and change the combination it won't work properly and only the default combination will unlock the lock.
Where are my errors here?
import java.util.Scanner;
public class Lock {
public static final int CLOCKWISE = 0;
public static final int COUNTER_CLOCKWISE = 1;
Scanner in = new Scanner(System.in);
private int x;
private int y;
private int z;
private boolean isLockOpen;
private int noOnTopOfKnob;
public Lock() {
x = 0;
y = 0;
z = 0;
this.isLockOpen = false;
this.noOnTopOfKnob = 0;
}
public void alterLockCombinaiton(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public void turnKnob(int direction, int noToStop){
int i = noOnTopOfKnob;
int numbersPassed = 0;
System.out.println("Simulating......");
do{
if(direction == CLOCKWISE)
i++;
else if(direction == COUNTER_CLOCKWISE)
i--;
if(i > 39)
i = 0;
if (i < 0)
i=39;
this.noOnTopOfKnob = i;
System.out.print(noOnTopOfKnob + " ");
numbersPassed++;
if(numbersPassed>40 && noOnTopOfKnob==noToStop)
break;
}
while(true);
System.out.println();
}
public void closeLock() {
System.out.println("Locked!");
this.isLockOpen = false;
}
public boolean openLock() {
// initializing with arbitrary values
int firstStop = -1;
int secondStop = -1;
int thirdStop = -1;
int firstRotation = -1;
int secondRotation = -1;
int thirdRotation = -1;
for(int i = 1; i <= 3; i++){
System.out.print("Enter a number (0-39) " + i + ": ");
int noToStop = in.nextInt();
System.out.print("Enter 0 for clockwise and 1 for counter-clockwise) " + i + ": ");
int direction = in.nextInt();
turnKnob(direction, noToStop);
if(i == 1) {
firstStop = noToStop;
firstRotation = direction;
}
else if(i == 2) {
secondStop = noToStop;
secondRotation = direction;
}
else if(i == 3) {
thirdStop = noToStop;
thirdRotation = direction;
}
if(firstStop == this.x && firstRotation == CLOCKWISE
&& secondStop == this.y && secondRotation == COUNTER_CLOCKWISE
&& thirdStop == this.z && thirdRotation == CLOCKWISE) {
this.isLockOpen = true;
}
}
return isLockOpen;
}
public boolean isLockOpen() {
return this.isLockOpen;
}
public int getNoAtTop() {
return noOnTopOfKnob;
}
}
END of Lock.java
import java.util.Scanner;
public class LockInput {
public static void main(String[] args) {
System.out.println("\nWelcome to lock simulator");
System.out.println("-------------------------------------------------");
menu();
}
public static void menu() {
Scanner scnr = new Scanner(System.in);
Lock newLock = new Lock();
int xInput, yInput, zInput;
System.out.println("\nSelect an option for the lock.\n");
System.out.println(" A : Set a new lock combination. ");
System.out.println(" B : Close the lock.");
System.out.println(" C : Attempt to open the lock.");
System.out.println(" D : Check lock status.");
System.out.println(" E : Check current top number.");
System.out.println(" Q : Quit program.");
char menuOption = scnr.next().charAt(0);
menuOption = Character.toUpperCase(menuOption);
switch(menuOption) {
case 'A':
System.out.println("Set a new combination for the lock.\n");
System.out.println("Enter the first number of the combination.");
xInput = scnr.nextInt();
System.out.println("Enter the second number of the combination.");
yInput = scnr.nextInt();
System.out.println("Enter the third number of the combination.");
zInput = scnr.nextInt();
newLock.alterLockCombinaiton(xInput,yInput,zInput);
menu();
break;
case 'B':
newLock.closeLock();
menu();
break;
case 'C':
newLock.openLock();
System.out.println("-------------------------------------------------");
System.out.println("After lock open attemp....");
System.out.println("No on top: " + newLock.getNoAtTop());
System.out.println("Lock is open: " + newLock.isLockOpen());
menu();
break;
case 'D':
System.out.println("Lock is open: " + newLock.isLockOpen());
menu();
break;
}
}
}
LockInput class is unfinished since I'm trying to figure out my input issue first.
The problem is that you are creating a new Lock() each time menu() is called.
So, the modified combination will be immediately replaced by the default one since menu() gets called just after that, and the lock replaced by a new Lock instance :
newLock.alterLockCombinaiton(xInput,yInput,zInput);
menu();
You may want to remove Lock newLock = new Lock(); from menu(), and declare it as a static variable at the class level instead :
static Lock newLock = new Lock();
Better yet, as suggested by #GhostCat to avoid the static variable :
Create the object in the main method
Lock newLock = new Lock();
Change the menu() method to menu(Lock newLock)
Then call it from main : menu(newLock);
The same goes for the Scanner variable, you'll probably figure that part out .
I've been trying to get this program to work for hours now. I managed to get the Fahrenheit to Celsius conversion to work, but for the life of me I can't do the same for the Celsius to Fahrenheit. I'm going to ask my teacher when school starts up again, but as of now I would appreciate some help. Here's my code.
import java.util.Scanner;
public class TempConvert {
public static void main(String[] args) {
//variables
double number;
int maxFahrenheit = 52;
int maxCelsius = 20;
Scanner keyboard = new Scanner(System.in);
//user input
System.out.println("Please enter 1 to convert from Fahrenheit to" +
" Celsius");
System.out.println("Please enter 2 to convert from Celsius to" +
" Fahrenheit");
number = keyboard.nextDouble();
//if else
if (number == 1) {
System.out.println("Celsius\t\tFahrenheit");
System.out.println("---------------------------");
int i;
double c;
for (i = 0, c = 0; i <= maxCelsius; i++, c++) {
System.out.println(i + "\t\t" + 9 * (i + 32) / 5);
} //end for
} //end if
else if (number == 2) {
System.out.println("Fahrenheit\t\tCelsius");
System.out.println("-----------------------------------");
int i;
double f;
for (i = 32, f = 32; i <= maxFahrenheit; i++, f++) {
System.out.println(i + "\t\t" + 5 * (f - 32) / 9);
} //end for
} //end else if
else {
System.out.println("Entry is invalid");
} //end else
} //end main
} //end TempConvert
You need to use a DecimalFormat df = new DecimalFormat("#.####");
Look i changed your code like this:
public static void main(String[] args) {
//variables
double number;
int maxFahrenheit = 52;
int maxCelsius = 20;
Scanner keyboard = new Scanner(System.in);
//user input
System.out.println("Please enter 1 to convert from Fahrenheit to" +
" Celsius");
System.out.println("Please enter 2 to convert from Celsius to" +
" Fahrenheit");
number = keyboard.nextDouble();
//if else
if(number == 1) {
System.out.println("Celsius\t\tFahrenheit");
System.out.println("---------------------------");
int i;
double c;
for(i = 0, c = 0; i <= maxCelsius; i++, c++) {
System.out.println(i + "\t\t" + 9 * (i + 32) / 5);
}//end for
}//end if
else if(number ==2) {
System.out.println("Fahrenheit\t\tCelsius");
System.out.println("-----------------------------------");
int i;
double f;
DecimalFormat df = new DecimalFormat("#.####");
for(i = 32, f = 32; i <= maxFahrenheit; i++, f++) {
System.out.println(i + "\t\t" + df.format(5 * (f - 32) / 9));
}//end for
}//end else if
else {
System.out.println("Entry is invalid");
}//end else
}//end main
}//end TempConvert
Look it works better like google and if you post this in google you will see 42 fahrenheit to celsius
42 = 5.55556
just as your tool =)
I am having issues with my gpa program where I have to use two arrays to store a grade and it's credits and calculate the gpa. So far, everything else seems to be working except the gpa wont calculate correctly and I am not sure what I am missing (probably simple).
My code thus far is:
Gpa class:
import java.util.*;
public class Gpa{
int[] credits = new int[4];
String[] grades = new String[4];
private int numCourses;
private int maxCourses;
private int sumOfCourses;
private int sumCredits;
private int sumPoints;
int newCredits;
int totalSum = 0;
int total = 0;
public Gpa(int noCourses){
maxCourses = noCourses;
numCourses = 0;
}
public void addCourse(int _newCredits, String newGrade){
for (int i=0; i<maxCourses; i++){
newCredits = _newCredits;
credits[i] = newCredits;
}
for (int i=0; i<maxCourses; i++){
grades[i] = newGrade;
}
switch (newGrade) {
case "A":
case "a":
newGrade = "4";
break;
case "B":
case "b":
newGrade = "3";
break;
case "C":
case "c":
newGrade = "2";
break;
case "D":
case "d":
newGrade = "1";
break;
case "F":
case "f":
newGrade = "0";
break;
}
sumPoints = sumPoints + (newCredits * Integer.parseInt(newGrade));
numCourses++;
}
public double calcGPA(){
for (int i=0; i<maxCourses; i++){
sumCredits = sumCredits + newCredits;
}
double gpa = (double)sumPoints/sumCredits;
return gpa;
}
} // end class
The tester class:
import java.util.Scanner;
public class GpaTestEx2
{
public static void main (String[] args)
{
//declarations
Scanner in = new Scanner(System.in); //input object
int numCourses; //number of courses - can be changed
int credits; //number of credits for a course
String grade; //grade for course
//read in number of courses
System.out.print("Enter number of courses: ");
numCourses = in.nextInt();
//create Gpa object to hold specified number of courses
Gpa myGPA = new Gpa(numCourses);
//read in all courses and add course information to Gpa object
for (int k=0; k<numCourses; k++)
{
System.out.print("Enter credits for course " + (k+1) + ": ");
credits = in.nextInt();
System.out.print("Enter grade for course " + (k+1) + ": ");
grade = in.next();
myGPA.addCourse(credits, grade);
}
//print results
System.out.println();
System.out.printf("GPA is %4.2f%n", myGPA.calcGPA( ));
} //end main
}
When I enter the course credits and grade it does not calculate the gpa correctly. For example, if the user input says there are 2 courses with one class having 4 credits with a grade of A and the other having 3 credits with a grade of B. I get a gpa of around 4.17 when it should be 3.57.
Any help would be great, I may or may not be missing something simple.
It seems like you are indexing into every element in your array every time someone inserts a value. We only need to change one element when a new grade is added. GPA class:
public class Gpa {
private int[] credits;
private String[] grades;
private int currentGrade;
public Gpa(int numGrades) {
credits = new int[numGrades];
grades = new String[numGrades];
currentGrade = 0;
}
public void addGrade(String letterGrade, int credit) {
grades[currentGrade] = letterGrade;
credits[currentGrade] = credit;
currentGrade = currentGrade + 1;
}
public double getGpa() {
double totalPoints = 0;
double totalWeight = 0;
for (int i = 0; i < currentGrade; i++) {
totalPoints = totalPoints + (letterToGpa(grades[i]) * credits[i]);
totalWeight = totalWeight + credits[i];
}
return totalPoints / totalWeight;
}
private double letterToGpa(String letter) {
char first = letter.toUpperCase().charAt(0);
switch (first) {
case 'A':
return 4.0;
case 'B':
return 3.0;
case 'C':
return 2.0;
case 'D':
return 1.0;
}
return 0.0;
}
}
The test class should work fine now:
public static void main(String[] args) {
Scanner in = new Scanner(System.in); //input object
int numCourses; //number of courses - can be changed
int credits; //number of credits for a course
String grade; //grade for course
//read in number of courses
System.out.print("Enter number of courses: ");
numCourses = in.nextInt();
//create Gpa object to hold specified number of courses
Gpa t = new Gpa(numCourses);
//read in all courses and add course information to Gpa object
for (int k=0; k<numCourses; k++)
{
System.out.print("Enter credits for course " + (k+1) + ": ");
credits = in.nextInt();
System.out.print("Enter grade for course " + (k+1) + ": ");
grade = in.next();
t.addGrade(grade, credits);
}
//print results
System.out.println();
System.out.printf("GPA is %4.2f%n", t.getGpa());
}
Just want to note that this clearly isn't the best way of doing this, nor does it follow Object Oriented patterns very well, but the OP's assignment requires we only use one class, etc.
.split() Method is NOT Allowed
I was got some help earlier from a helpful guy! I was just wondering if anyone could help me modify this a little bit more,
The code is meant for an assignment and It is based on the input from the scanner. It has two other classes but this is the one of interest.
The code is working at the moment, however The things that have to be input are things like **U5, D10** etc. That works fine. However I need the code to be able to read multiple String off one one line whilst seperating them like they are now. Like say for example **D10 U5 L4**, all from one line for just one player out of two. The code at the moment is not recognizing it as one line and instead if assigning the second typed thing to the second player.
Any tips?
Thanks
import java.util.Scanner;
class Asgn2
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
Player me = new Player("Player1");
Player opponent = new Player("player2");
int startingLoop = 0;
String strA;
int turn =1;
System.out.print("How many turns will the game have: ");
int turnsInGame = scan.nextInt();
System.out.print("How many moves does each player have each turn: ");
int numberOfTurns = scan.nextInt();
for(int i = turnsInGame; startingLoop < i; startingLoop++)
{
System.out.print("Turn " + turn++ + "\n");
System.out.print("Player 1 what are your " + numberOfTurns + " move(s): ");
String userInput = scan.next();
System.out.print("Player 2 what are your " + numberOfTurns + " move(s): ");
String userInputOne = scan.next();
for (int j = 0; j < userInput.length() - 1; j++)
{
char letter = userInput.charAt(j);
String num = "";
for(int k= j + 1; k < userInput.length(); k++)
{
j++;
if(userInput.charAt(k)!=' ')
{
num+=userInput.charAt(k);
}
else
{
break;
}
}
int integer = Integer.parseInt(num + "");
strA = Character.toString(letter);
switch(strA) //For player oneChooses which value to add or subtract from based on what is input.
{
case "U":
me.move(moveSteps.UP , integer);
break;
case "D":
me.move(moveSteps.DOWN, integer);
break;
case "L":
me.move(moveSteps.LEFT, integer);
break;
case "R":
me.move(moveSteps.RIGHT, integer);
break;
}
//Player 2
for (int playerTwo = 0; playerTwo < userInputOne.length() - 1; playerTwo++)
{
char letterTwo = userInputOne.charAt(0);
String numTwo = "";
String strB = Character.toString(letterTwo);
for(int m= playerTwo + 1; m<userInput.length(); m++)
{
playerTwo++;
if(userInputOne.charAt(playerTwo)!=' ')
{
numTwo+=userInputOne.charAt(playerTwo);
}
else
{
break;
}
}
int stepsMoved = Integer.parseInt(numTwo + "");
switch(strB) //For player two
{
case "U":
opponent.move(moveSteps.UP , stepsMoved);
break;
case "D":
opponent.move(moveSteps.DOWN, stepsMoved);
break;
case "L":
opponent.move(moveSteps.LEFT, stepsMoved);
break;
case "R":
opponent.move(moveSteps.RIGHT, stepsMoved);
break;
}
}
}
System.out.print(me);
System.out.print(opponent);
}
}
}
Once you assign the input to a String, use the .split() method to split the string into an array. To use the .split(), put in the character you want to split it with. In this case a space. For example use this for your current project: .split(" "). Once you split it, you can access it just like any array.
Update:
first use the .nextLine() and assign it to a temporary string variable. Then
you can create another scanner and put a string in. For example:
Scanner sc = new Scanner(YOUR TEMPORARY VARIABLE);
you can now use the .next() to get individual strings.
Here is the Asgn2 class
import java.util.Scanner;
public class Asgn2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What is your name player 1: ");
String p1name = scan.nextLine();
System.out.print("What is your name player 2: ");
String p2name = scan.nextLine();
Player p1 = new Player(p1name);
Player p2 = new Player(p2name);
System.out.print("How many turns will the game have: ");
int numTurns = scan.nextInt();
System.out.print("How many moves does each player have each turn: ");
int numMoves = scan.nextInt();
for (int turn = 1; turn <= numTurns; turn++) {
System.out.println("----------------");
System.out.println("Turn number " + turn);
System.out.println("----------------");
for (int player = 1; player <= 2; player++) {
System.out.print("Player " + player + " what are your " + numMoves + " move(s): ");
for(int move=1;move<=numMoves;move++){
String currMove = scan.next();//splits at space;
char dir = currMove.charAt(0);//gets dir
String temp="";
for(int index=1;index<currMove.length();index++){
temp+=currMove.charAt(index);
}
int dist = Integer.parseInt(temp);
if(player==1){
p1.move(dir, dist);
}else if(player==2){
p2.move(dir, dist);
}
}
System.out.println("Player 1 is at " + p1.getPos() + " and Player 2 is at " + p2.getPos());
System.out.println();
}
}
}
}
And here is the Player class
public class Player {
private String name;
private int locX = 0;
private int locY = 0;
public Player(String name) {
this.name = name;
}
public void move(char dir, int numSteps) {
switch (dir) {
case 'U':
locY += numSteps;
break;
case 'D':
locY -= numSteps;
break;
case 'L':
locX -= numSteps;
break;
case 'R':
locX += numSteps;
break;
}
}
public String getPos() {
return "(" + locX + ", " + locY + ")";
}
public String getName() {
return name;
}
}
And before anyone goes and says that posting blocks of code does not help OP, I am in a chatroom with him in which I explain this stuff, so dont hate :)
call the method .nextLine() instead of .next(). I think that should solve your problem.