Java Bot saves Princess Challenge - java

Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move one step at a time in any of the four directions. Can you rescue the princess?
Input format
The first line contains an odd integer N (3 <= N < 100) denoting the size of the grid. This is followed by an NxN grid. Each cell is denoted by '-' (ascii value: 45). The bot position is denoted by 'm' and the princess position is denoted by 'p'.
Grid is indexed using Matrix Convention
Output format
Print out the moves you will take to rescue the princess in one go. The moves must be separated by '\n', a newline. The valid moves are LEFT or RIGHT or UP or DOWN.
Here is my code:
package challenges;
import java.util.*;
public class Solution {
static void displayPathtoPrincess(int n, int p,String [][] grid){
int botRow=0,botCol=0;
for(int r=0;r<n;r++){
for (int c = 0; c < grid.length; c++) {
if(grid[r][c].equals('m')) {
botRow=r;
botCol=c;
continue;
}
}
if(grid[0][0].equals('P')) {
while(botRow>0) {
botRow--;
System.out.println("UP\n");
}
while(botCol>0) {
botCol--;
System.out.println("LEFT\n");
}
}
else if(grid[0][p-1].equals('P')) {
while(botRow>0) {
System.out.println("UP\n");
botRow--;
}
while(botCol<p-1) {
botCol++;
System.out.println("RIGHT\n");
}
}
else if(grid[n-1][0].equals('P')) {
while(botRow<n-1) {
botRow++;
System.out.println("DOWN\n");
}
while(botCol>0) {
botCol--;
System.out.println("LEFT\n");
}
}
else if(grid[n-1][p-1].equals('P')) {
while(botRow<n-1) {
botRow++;
System.out.println("DOWN\n");
}
while(botCol<p-1) {
botCol++;
System.out.println("RIGHT\n");
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
n=m;
int j=0;
String grid[][] = new String[m][n];
for(int i = 0; i < m; i++) {
while(j<n){
grid[i][j] = in.next();
j++;
}
}
displayPathtoPrincess(m,n,grid);
}
}
Its giving Null Pointer Exception.can anyone please tel what am i doing wrong in here?

Try this solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine());
char grid[][] = new char[m][m];
for(int i = 0; i < m; i++)
{
String line = br.readLine();
grid[i] = (line.trim()).toCharArray();
}
displayPathtoPrincess(m, grid);
}
static void displayPathtoPrincess(int m, char[][] grid)
{
int botRow = 0, botCol = 0, princessRow = 0, princessCol = 0;
// Get bot and princess coordinates
for (int r = 0; r < m; r++)
{
for (int c = 0; c < grid.length; c++)
{
if (grid[r][c] == 'm' || grid[r][c] == 'M')
{
botRow = r;
botCol = c;
}
else if (grid[r][c] == 'p' || grid[r][c] == 'P')
{
princessRow = r;
princessCol = c;
}
}
}
// Move the bot up or down till bot reaches same row
if( princessRow < botRow )
{
while(botRow != princessRow)
{
botRow--;
System.out.println("UP");
}
}
else if( princessRow > botRow )
{
while(botRow != princessRow)
{
botRow++;
System.out.println("DOWN");
}
}
// Move the bot left or right till bot reaches same column
if( princessCol < botCol )
{
while(botCol != princessCol)
{
botCol--;
System.out.println("LEFT");
}
}
else if( princessCol > botCol )
{
while(botCol != princessCol)
{
botCol++;
System.out.println("RIGHT");
}
}
}
}

Ok, no offence but this code is a mess.
I know what I will answer won't be exactly what you want, but it might be very helpful for you in the future.
What would I change? (After you change all of this, the error will more likely become apparent or it will be clear enough to ask for help)
First: Variable types.
This is just a tiny detail, but I don't like the way you did it; why use a String if every cell will be represented by a char?
Every time you create a variable (or an Array, or anything at all) think about what you need it to store, and create the variable in a way it will store what you need. If you needed it to store if something is true or false, you wouldn't create a String variable and store "true" or "false", you would use a boolean.
Apply this every time and you will improve faster.
Second: use functions.
Functions are a great way to abstract yourself from the implementation details.
I mean, you can easily see the difference between something like your code, and something like:
static void displayPathtoPrincess(int n, int p,char [][] grid){
Point bot;
Point princess;
getInitialPositions(bot, princess, grid);
Point dif = getRelativePrincessPosition(bot, princess);
while (!bot.equals(princess)) {
switch (dif.y) {
case UP:
move (UP_MOVEMENT);
break;
case DOWN:
move (DOWN_MOVEMENT);
break;
}
switch (dif.x) {
case LEFT:
move(LEFT_MOVEMENT);
break;
case RIGHT:
move(RIGHT_MOVEMENT);
break;
}
}
}
(And then implement the necessary methods, and create the constants, that is something pretty easy to do)
Third: use the appropriate loop every time.
If you know you want to go from j = 0, while j < n, increasing j every iteration; that's not called a while, that's called a for. (Also, as someone else commented in their answer, you forgot to restart the j; so it only goes in once.
Finally: Let's go with your error now.
I believe your code might be pretty buggy and not give you the desired output, but the NullPointerException is something more specific.
Since you don't use the appropriate loop in the main, for j, and you forgot to restart it's value, you didn't fill the whole array.
When you try to read a value you didn't fill (in the for where you find the robot's position), that value is null, and the value for some rows will be null too; hence the NullPointerException (because you try to access the value of a null array).

While taking input you have to make j =0 every time you are coming out of while loop as
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
n=m;
int j=0;
String grid[][] = new String[m][n];
for(int i = 0; i < m; i++) {
j = 0;
while(j<n){
grid[i][j] = in.next();
j++;
}
}
i remains 0 due to this mistake.
You should put print statement to check why are you getting error.

here is the solution..
import java.util.*;
public class Solution {
static void displayPathtoPrincess(int n, int p, String[][] grid) {
int botRow = 0, botCol = 0;
for (int r = 0; r < n; r++) {
for (int c = 0; c < grid.length; c++) {
if (grid[r][c].equalsIgnoreCase("m")) {
botRow = r;
botCol = c;
}
}
if (grid[0][0].equalsIgnoreCase("P")) {
while (botRow > 0) {
botRow--;
System.out.println("UP\n");
}
while (botCol > 0) {
botCol--;
System.out.println("LEFT\n");
}
} else if (grid[0][p - 1].equalsIgnoreCase("P")) {
while (botRow > 0) {
botRow--;
System.out.println("UP\n");
}
while (botCol < p - 2) {
botCol++;
System.out.println("RIGHT\n");
}
} else if (grid[n - 1][0].equalsIgnoreCase("P")) {
while (botRow < n - 2) {
botRow++;
System.out.println("DOWN\n");
}
while (botCol > 0) {
botCol--;
System.out.println("LEFT\n");
}
} else if (grid[n - 1][p - 1].equalsIgnoreCase("P")) {
while (botRow < n - 2) {
botRow++;
System.out.println("DOWN\n");
}
while (botCol < p - 2) {
botCol++;
System.out.println("RIGHT\n");
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
int j;
String grid[][] = new String[m][m];
for(int i = 0; i < m; i++) {
for(j=0;j<m;j++){
grid[i][j] = in.next();
}
}
displayPathtoPrincess(m,m,grid);
}
}

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static void nextMove(int n, int r, int c, String [] grid){
int xcord=0;
int ycord=0;
for ( int i = 0 ; i <n-1; i++){
String s = grid[i];
xcord=i;
for(int x =0; x<=n-1;x++){
if(s.charAt(x)=='p'){
ycord=x;
if(xcord==r){
if(ycord>c){System.out.println("RIGHT");return;}
else {System.out.println("LEFT");return;}
}else if(xcord<r){System.out.println("UP");return;}
else{ System.out.println("DOWN");return;}
}
}
}
System.out.println(xcord);
System.out.println(ycord);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n,r,c;
n = in.nextInt();
r = in.nextInt();
c = in.nextInt();
in.useDelimiter("\n");
String grid[] = new String[n];
for(int i = 0; i < n; i++) {
grid[i] = in.next();
}
nextMove(n,r,c,grid);
}
}

You might wish to take a look at the following code in Java:
import java.util.Scanner;
public class Solution {
/*
*
*/
static void printPath(int n, String moves) {
for (int i = n / 2; i >= 0; i -= 2) {
System.out.println(moves);
}
}
/*
*
*/
static void displayPathtoPrincess(int n, String [] grid){
// **** princess # top left ****
if (grid[0].substring(0, 1).equals("p")) {
printPath(n, "UP\nLEFT");
}
// **** princess # top right ****
else if (grid[0].substring(n - 1, n).equals("p") ) {
printPath(n, "UP\nRIGHT");
}
// **** princess # bottom right ****
else if (grid[n - 1].substring(n - 1, n).equals("p")) {
printPath(n, "DOWN\nRIGHT");
}
// **** princess # bottom left ****
else {
printPath(n, "DOWN\nLEFT");
}
}
/*
* Test code
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m;
m = in.nextInt();
String grid[] = new String[m];
for(int i = 0; i < m; i++) {
grid[i] = in.next();
}
// **** ****
in.close();
// **** ****
displayPathtoPrincess(m,grid);
}
}

Related

movie ticket booking in a particular row using array

We have to check the seat availability and book two consecutive tickets in the same row.
If tickets are not available or If two tickets booked from two different rows then we have to throw an exception (using arrays)
Condition 1: if i select 7th and 8th seat, as it is from different row we are not supposed to allow them.
Condition 2: if i enter the seat as 100 and 101, as the specified seats are not available , we are not supposed to book the seats.`
It would be great, if someone could help out on this,
package demo;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class Newtable {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int twoDm[][] = new int[5][7];
int i, j, k = 1, m = 2;
int ab = 0;
int firstticket;
int secondticket;
boolean firstTicketFlag = false;
boolean secondTicketFlag = false;
for (i = 0; i < 5; i++) {
for (j = 0; j < 7; j++) {
twoDm[i][j] = k;
k++;
}
}
for (int[] row : twoDm) {
printRow(row);
}
// this loop repeats the reserving process (and printing seats) 5 times
for (int l = 0; l < 5; l++) {
System.out.print("Enter the Seats number to reserve: ");
firstticket = Integer.parseInt(br.readLine());
secondticket = Integer.parseInt(br.readLine());
firstTicketFlag = containsCheck(twoDm, firstticket);
secondTicketFlag = containsCheck(twoDm, firstticket);
if (firstTicketFlag && secondTicketFlag) {
if (firstticket == (secondticket - 1)) {
k = 1;
m = 2;
for (i = 0; i < 5; i++) {
for (j = 0; j < 7; j++) {
if (k == firstticket && m == secondticket) {
// here we check if the seat has already been
// reserved
ab = m - 1;
if (twoDm[i][j] == 0 && twoDm[i][j+1] == 0) {
throw new Exception("That seat has already been reserved");
}
// if its not reserved then reserve it
else {
//ab = m - 1;
twoDm[i][j] = 0;
twoDm[i][j+1] = 0;
}
}
k++;
m++;
}
}
// print updated array of seats
for (int[] row : twoDm) {
printRow(row);
}
} else {
throw new Exception(" select two seats in the same row");
}
} else {
System.out.println("Please enter the available seat numbers");
}
}
}
private static boolean containsCheck(int[][] twoDm, int ticket) {
// TODO Auto-generated method stub
boolean flag = false;
for (int[] a : twoDm) {
if (a.equals(ticket)) {
flag = true;
}
}
return flag;
}
}
The secondTicketFlag is not checked correctly:
secondTicketFlag = containsCheck(twoDm, firstticket);
//should be
secondTicketFlag = containsCheck(twoDm, secondticket);
containsCheck needs another for loop to check the individual values of every seat inside the row (one dimensional array):
private static boolean containsCheck(int[][] twoDm, int ticket) {
// TODO Auto-generated method stub
boolean flag = false;
// added another for loop, and changed "equals" to == since the values are int
for (int[] oneDm : twoDm) {
for (int individualSeat : oneDm) {
if (individualSeat == ticket) {
flag = true;
}
}
}
return flag;
}
And if the first seat OR the second seat is booked then you want to return error,
if (twoDm[i][j] == 0 && twoDm[i][j+1] == 0)
//should be
if (twoDm[i][j] == 0 || twoDm[i][j+1] == 0)
Sorry for any formatting mistakes(first time commenting) and hopefully that solves the problem you had.
EDIT: You have various ways to check that the seats are on the same row, given the way you are putting the values of the seats, I would use the remainder (%) operator
If the first seat has a remainder different from 0 that means that the two seats are on the same row (the first seat must be between 1-6, 8-13, 15-20... it can't be a multiple of 7), you could also use the j value on the for loop. That's up to you. The way to check the remainder:
if(firstticket % 7 == 0){ System.out.println("The seats are not in the same row");}

ACM-ICPC 7384 programming challenge

I'm trying to solve the Popular Vote problem, but I get runtime error and have no idea why, I really appreciate the help. Basically my solution is to get the total of votes, if all candidates have the same amount of votes; then there's no winner, otherwise I calculate the percentage of votes the winner gets in order to know if he's majority or minority winner.
import java.util.Scanner;
class popular {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos=s.nextInt();
int cont=0;
int ganador=0;
float num=0;
while(cont!=casos){
n=s.nextInt();
int votos[]= new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
suma=sumar(votos);
if(suma==-1){
System.out.println("no winner");
}
else{
ganador=ganador(votos, suma);
num=(float)votos[ganador]/(float)suma;
if( num> 0.5){
System.out.println("majority winner "+(ganador+1));
}
else{
System.out.println("minority winner "+(ganador+1));
}
}
cont++;
ganador=0;
}
}
public static int sumar(int arreglo[]){
int resp1=-1, resp=0;
int temp=arreglo[0];
boolean sol=true;
for (int i = 0; i < arreglo.length; i++) {
resp=resp+arreglo[i];
if(temp!=arreglo[i]){
sol=false;
}
}
if(sol==false){
return resp;
}
return resp1;
}
public static int ganador(int arreglo[], int suma){
int mayor=0;
int ganador=0;
for (int i = 0; i < arreglo.length; i++) {
if(arreglo[i]>mayor){
mayor=arreglo[i];
ganador=i;
}
}
return ganador;
}
}
I submitted your code to the OJ, but I didn't get a runtime error, but I got Compilation error. I have to figure out there are some problems in your code. First of all, if you want to submit a java code to OJ, you need to name the public class as Main instead of popular or something else. Second, your code logic is not correct. Suppose a test case:
4
1
1
2
2
Your program will print "minority winner 3" but it's should be "no winner".
Here is a modified source code from yours (you can get accepted with this code):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos = s.nextInt();
int cont = 0;
int ganador = 0;
float num = 0;
while (cont != casos) {
n = s.nextInt();
int votos[] = new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
ganador = findMaximum(votos);
if (getMaximumCount(votos, votos[ganador]) > 1) {
System.out.println("no winner");
} else {
suma = sumOf(votos);
if (votos[ganador] * 2 > suma) {
System.out.println("majority winner " + (ganador + 1));
} else {
System.out.println("minority winner " + (ganador + 1));
}
}
cont++;
ganador = 0;
}
}
private static int sumOf(int[] arreglo) {
int sum = 0;
for (int x : arreglo) {
sum += x;
}
return sum;
}
private static int getMaximumCount(int[] arreglo, int maximum) {
// Check if there are more than one items have the maximum value
int count = 0;
for (int x : arreglo) {
if (x == maximum) {
count++;
}
}
return count;
}
private static int findMaximum(int[] arreglo) {
int x = 0, pos = 0;
for (int i = 0; i < arreglo.length; i++) {
if (x < arreglo[i]) {
x = arreglo[i];
pos = i;
}
}
return pos;
}
}
Hope it could help you!

i can't show the output to the user

I wrote this code but every time I try to show the output to the user by a System.out.print statement something goes wrong.
The purpose of the code is to check if the array is "palindromic".
import java.util.Scanner;
public class u {
public static void main(String[] args) {
int [] arr = {1,2,3,4,3,2,1};
int counter1 = 0,counter2 = arr.length-1;
int x = arr.length/2;
while (counter1 < x ) {
if (arr[counter1] == arr [counter2]){
counter1++;
counter2--;
} else {System.out.println(":("); break;}
}
System.out.println("Bingo!");
}}
If the problem is that the program always prints "Bingo!" it's because break only ends the while loop. And the "Bingo!" line is outside the while loop so it will still be called. You can avoid this by either change break to return. You can also use labels:
x: {
while(...) {
...
else break x;
}
System.out.println("Bingo!");
}
import java.util.Scanner;
public class u {
public static void main(String[] args) {
boolean d = false;
int [] arr = {2,9,3,4,4,3,9,2};
int counter1 = 0,counter2 = arr.length-1;
int x = arr.length/2;
while (counter1 < x ) {
d = false;
if (arr[counter1] == arr [counter2]){
counter1++;
counter2--;
d = true;
} else break;
}
if (d)
System.out.println("Bingo!");
else System.out.println(":(");
}}

Magic Square Method needs to output if it is a magic square and the sum of rows and columns

I'm working on an assignment that takes a data file with a number matrix and determines if it is a magic square. If it is then it also needs to report the sum of the rows and columns. With the output:
The matrix is a magic square.
The sum of all the rows and columns is 34.
I'm not sure how to go about this with one method, I feel like its asking me to return 2 values. The closest I have came is by adding a System.out.println with the sum at the end of my method when it returns true.
But the issue with that is that my output is backwords:
The sum of all the rows and columns is 34.
The matrix is a magic square.
How do I get the sum when I've only been asked to create one method? Below is my code, the instructor gave the bottom 3 methods so I'm only concerned with the first 2.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class chp8magic
{
public static void main(String args[])
{
int matrix[][] = initMatrix();
printData(matrix);
if (isMagic(matrix)) {
System.out.println("The matrix is a magic square.");
}
else {
System.out.println("Not a magic square");
}
}
public static boolean isMagic(int[][] mat)
{
int n = mat.length;
int nSquare = n*n;
int M = (n*n*(n*n+1)/2)/n;
int sumRow = 0, sumColoumns = 0, sumPriDiag = 0, sumSecDiag = 0;
boolean[] flag = new boolean[n*n];
for(int row = 0; row < n; row++){
sumRow = 0;
sumColoumns = 0;
for(int col = 0; col < n; col++)
{
if( mat[row][col] < 1 || mat[row][col] > nSquare )
return false;
if(flag[mat[row][col]-1] == true)
return false;
flag[mat[row][col]-1] = true;
sumRow += mat[row][col];
sumColoumns += mat[col][row];
}
sumPriDiag += mat[row][row];
sumSecDiag += mat[row][n-row-1];
if(sumRow!=M || sumColoumns!=M)
return false;
}
if(sumPriDiag!=M || sumSecDiag!=M)
return false;
else
return true;
}
public static int[][] initMatrix()
{
int matrix[][];
Scanner filein = null;
try {
filein = new Scanner(new File("matrix.txt"));
int numRows = Integer.parseInt(filein.nextLine());
matrix = new int[numRows][];
parseData(matrix, filein);
filein.close();
return matrix;
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
if(filein != null)
filein.close();
return null;
}
}
public static void parseData(int matrix[][], Scanner in)
{
for(int r = 0; r < matrix.length; r++)
{
String splitLine[] = in.nextLine().split(" ");
matrix[r] = new int[splitLine.length];
for(int c = 0; c < matrix[r].length; c++){
matrix[r][c] = Integer.parseInt(splitLine[c]);
}
}
}
public static void printData(int matrix[][])
{
for(int r = 0; r < matrix.length; r++){
for(int c = 0; c < matrix[r].length; c++){
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
Probably you just need to do:
System.out.println("is magic: " + isMagic);
System.out.ptintln("sum: " + sum);
However this is not really returning the values, just printing them. To return two values there are several options. You could return an object:
public class MagicSquareProperties {
private boolean magic;
private int sum;
public MagicSquareProperties(boolean magic, int sum) {
this.magic = magic;
this.sum = sum;
}
public boolean isMagic() {
return magic;
}
public int getSum() {
return sum;
}
}
// now to return both values: return new MagicSquareProperties(true, 34);
But in my opinion the best solution would be the following:
Create a class MagicSquare.
Add property declarations (e.g. private int sum).
Add a constructor, for example MagicSquare(File file), this constructor reads the file and populates the properties.
Add getters and setters if needed (e.g. getSum())
Execute the main method in another class and call new MagicSquare(...) to create a magic square object. Afterwards you can call the getters on the object whenever you need the value.

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

Categories

Resources