Creating a string from loop results in java - java

I need to be able to save the loop results to a string to be able to manipulate the user output. No arrays
I've attempted to convert to string inside the loop which does not make much sense. I can't figure another way to save the results unless I make another method. I am not allowed create arrays.
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter phone number: ");
String number = input.nextLine();
String phone ="";
for (int i = 0; i < number.length(); i++){
if (Character.isLetter(number.charAt(i)))
phone = getNumber(Character.toUpperCase(number.charAt(i)));
else
number.charAt(i);
}
System.out.println("Your number is " + phone);
}
public static int getNumber(char uppercaseLetter){
if (uppercaseLetter >= 'W' && uppercaseLetter <= 'Z')
return 9;
else if (uppercaseLetter >= 'T' && uppercaseLetter < 'W')
return 8;
else if (uppercaseLetter >= 'P' && uppercaseLetter < 'T')
return 7;
else if (uppercaseLetter >= 'M' && uppercaseLetter < 'P')
return 6;
else if (uppercaseLetter >= 'J' && uppercaseLetter < 'M')
return 5;
else if (uppercaseLetter >= 'G' && uppercaseLetter < 'J')
return 4;
else if (uppercaseLetter >= 'D' && uppercaseLetter < 'G')
return 3;
else
return 2;
}
}
should look like: ie. 352-hey-call =
"Your number is 352-439-2255"

Actually, for each char you're looking for the corresponding letter or number, but you don't use it, you need to append them together. Using += operator on String, but as it's in a loop for better performance it's recommended to use a StringBuilder
StringBuilder phone = new StringBuilder();
for (int i = 0; i < number.length(); i++){
if (Character.isLetter(number.charAt(i))){
phone.append(getNumber(Character.toUpperCase(number.charAt(i))));
}else{
phone.append(number.charAt(i));
}
}
System.out.println("Your number is " + phone.toString());

Related

Find the number of substring of a string that satisfy a criteria

Question:
Given a string a, find the number of subsegments of the string that contain at least one vowel AND one consonant. For example : input "blue" will have number of subsgments = 1, "hackerrank" will return number of segments = 3 ("ha","cker","rank") each will contain at least one consonant and one vowel.
Here is my code in Java
public static int segments(String password){
int numbersegments = 0;
int vowel = 0;
int consonant = 0;
for(int index = 0; index < password.length();index++){
if(password.charAt(index) == 'a' || password.charAt(index) == 'e' ||
password.charAt(index) == 'i' || password.charAt(index) == 'u'
|| password.charAt(index) == 'o' ){
vowel++;
}
else
consonant++;
if(vowel >= 1 && consonant >= 1){
numbersegments++;
vowel = 0;
consonant = 0;
}
}
return numbersegments;
}
I run the test cases with code above and it shows 5 out of 15 ouputs are correct. Unfortunately i can't see the input for those incorrect testcases so there is no way i can see the missing logic for my code above to run 100% correct on all cases. Maybe i didn't take into account certain edge cases but i cannot think of any. Is there any flaw of my code above ? Is there any missing cases that i forget to take into account ? Thank you
Try this, I think it will work
public static int segments(String password){
int numbersegments = 0;
int vowel = 0;
int consonant = 0;
password = password.toLowerCase();
for(int index = 0; index < password.length();index++){
if(password.charAt(index) == 'a' || password.charAt(index) == 'e' ||
password.charAt(index) == 'i' || password.charAt(index) == 'u'
|| password.charAt(index) == 'o' ){
vowel++;
}
else if(password.charAt(index)>='a' && password.charAt(index)<='z')
consonant++;
if(vowel >= 1 && consonant >= 1){
numbersegments++;
vowel = 0;
consonant = 0;
}
}
return numbersegments;
}
You did not take into consideration CAPs, special characters & numbers. you check small letter vowels only.

Evaluating infix expressions of unsigned integers using 2 stacks and getting wrong answer

I'm writing a program for class, that as the title says, evaluates infix expressions of unsigned integers using two stacks. The division should be integer division which is why the numbers are integers and not Double. I have created a GUI that gets input from the user and should return the answer. I have attached an ActionListener to the button to compute using this code:
result = Evaluate.evalExp(txtExp.getText());
txtResult.setText(result + "");
The problem is that when I run the program I don't get the correct answer.
For 3-4 I'll get 3, for 6/2 I get 2, and for anything that has parenthesis I get 0 for the answer. I have been trying to figure this out for the better part of the day without any results. I'm hoping someone here will be able to help.
import java.util.Stack;
public class Evaluate {
public static int evalExp(String input) {
char[] tokens = input.toCharArray();
Stack<Integer> number = new Stack<Integer>();
Stack<Character> operator = new Stack<Character>();
int holder = 0;
int ans;
for (int i=0; i < tokens.length; i++) {
// checking to see if token is a number
if (tokens[i] >= '0' && tokens[i] <= '9') {
StringBuffer num = new StringBuffer();
// need to check if number is more than one digit long
while ( i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
num.append(tokens[i++]);
number.push(Integer.parseInt(num.toString()));
}
else if (tokens[i] == '(')
operator.push(tokens[i]);
else if (tokens[i] == ')') {
while (operator.peek() != '(') {
holder = applyOp(operator.pop(), number.pop(), number.pop());
number.push(holder);
}
operator.pop();
}
else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') {
// check for precedence
while (!operator.empty() && hasPrecedence(tokens[i], operator.peek())) {
holder = applyOp(operator.pop(), number.pop(), number.pop());
number.push(holder);
}
operator.push(tokens[i]);
}
} // end for loop
while (!operator.empty()) {
holder = applyOp(operator.pop(), number.pop(), number.pop());
number.push(holder);
}
ans = number.pop();
return ans;
} // end of evalExp
// checks to see which operand has a higher precedence if any
public static boolean hasPrecedence(char op1, char op2) {
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
} // end hasPrecedence
// return result of operator and operands
public static int applyOp(char op, int b, int a) {
int ans = 0;
switch (op) {
case '+': ans = (a + b);
// return ans;
break;
case '-': ans = (a - b);
// return ans;
break;
case '*': ans = (a * b);
// return ans;
break;
case '/': ans = (a / b);
if (b == 0)
throw new ArithmeticException("Cannot divide by zero");
// return ans;
break;
}
return ans;
} //end applyOp
} //end Class Evaluate
Debugging the same would have given you the answer.
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
{
num.append(tokens[i++]);
}
In this code when you do i++, you have incremented the value of i but did not handle the char over there which is an operator in your use case.
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
{
num.append(tokens[i++]);
}
if (i != tokens.length)
i--;
Reverting the increment of the index fixes this issue. This may not be right solution. Just wanted to show the impact of the incremented index.

the method does not display as supposed in method

I created a class like this
public Move(char colour, int number) //a constructor takes 2 input
{
this.colour = colour;
this.number = number;
}
public static int convertColourtoNum(char colour)
{
int index = 0;
if (colour == 'R')
index = '0';
else if (colour == 'Y')
index = '1';
else if (colour == 'G')
index = '2';
else
index = '3';
return index; //return the colour in type int after being converted
}
then in other class I use this method to display
Move m = new Move('R', 4);
System.out.println("Display " + m.convertColourtoNum(m.getColour()));
The problem is the code is supposed to display
Display 0
but instead, it displays
Display 48
Why does it happen? Thank you
The problem lies in our method convertColourToNum
if (colour == 'R')
index = '0';
else if (colour == 'Y')
index = '1';
else if (colour == 'G')
index = '2';
else
index = '3';
Notice how you used '' around the numbers. This makes java think that you have a char, so it is actually returning the ASCII value for 0 and storing it in index. What you should be doing instead is
if (colour == 'R')
index = 0;
else if (colour == 'Y')
index = 1;
else if (colour == 'G')
index = 2;
else
index = 3;
That way, java realizes that you want the int data type, and will store an int in index.

Check content of array before acting

The purpose of this program is to build a 10x10 array grid made out of periods (.), allow the user to designate a starting point, and then the program will randomly choose numbers which are assigned to directions for the 'walker' to go. Each time it moves it marks its spot with the next letter in the alphabet (the starting point is marked by A). If the walker crosses out of the bounds of the array (AKA > 10 or < 0) it will say "you were arrested" and if the variable alpha == 'Z' it way say "You made it home".
The only thing I have left to do is make it so that if the walker tries to go back to a spot it has already been to, it will skip to the next space until it reaches a space it hasn't been.
package walktester;
import java.lang.Math;
import java.util.Random;
import java.util.Scanner;
class DrunkWalker {
private char[][] walkgrid = new char[10][10];
private static int randNSEW;
private int randomnum;
private int startrow;
private int startcol;
private char alpha = 'A';
private int nextrow;
private int nextcol;
public DrunkWalker(int r, int c) {
startrow = r;
startcol = c;
nextrow = startrow;
nextcol = startcol;
for (int i = 0; i < 10; i ++) {
for (int j = 0; j < 10; j++)
walkgrid[i][j] = '.';
}
walkgrid[r][c] = alpha++;
}
public static void getRand(){
int x100 = 0;
double randomNum = 0.0;
randomNum = Math.random();
x100 = (int) (randomNum * 100);
randNSEW = x100 % 4;
}
public int getNextRow(){
return nextrow;
}
public int getNextCol(){
return nextcol;
}
public boolean processing(){
for(int i = 0; i < 25; i ++){
getRand();
if(randNSEW == 0){
nextcol--;
}
if(randNSEW == 1){
nextrow++;
}
if(randNSEW == 2){
nextcol++;
}
if(randNSEW == 3){
nextrow--;
}
if(nextrow < 0 || nextrow >= 10 || nextcol < 0 || nextcol >= 10) {
return false;
}
walkgrid[nextrow][nextcol] = alpha++;
}
return true;
}
public char[][] DisplayGrid() {
for(int y = 0; y < 10; y++) {
for(int x = 0; x < 10; x++) {
System.out.print(walkgrid[x][y] + " ");
}
System.out.println();
}
return walkgrid;
}
}
public class WalkTester {
public static void main(String[] args) {
Scanner inpr = new Scanner(System.in);
Scanner inpc = new Scanner(System.in);
Scanner inpchoice = new Scanner(System.in);
int r = 0;
int c = 0;
char choice = 'y';
while(choice == 'y' || choice == 'Y') {
System.out.println("Please enter x coordinate between 1 and 10.");
r = inpr.nextInt();
r = r - 1;
System.out.println("Please enter y coordinate between 1 and 10");
c = inpr.nextInt();
c = c - 1;
if(r < 0 || r > 9 || c < 0 || c > 9){
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
DrunkWalker drunkwalker = new DrunkWalker(r, c);
boolean walkerSucceeded = drunkwalker.processing();
drunkwalker.DisplayGrid();
if(walkerSucceeded) {
System.out.println("You made it home");
} else {
System.out.println("You were arrested");
}
System.out.println("Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
}
}
By "skip to the next space until it reaches a space" I assume you mean they continue on in the same direction.
So, just before you do:
walkgrid[nextrow][nextcol] = alpha++;
you need to check:
if (walkgrid[nextrow][nextcol] == '.')
so something along these lines:
...
do {
if (randNSEW == 0) nextcol--;
if (randNSEW == 1) nextrow++;
if (randNSEW == 2) nextcol++;
if (randNSEW == 3) nextrow--;
if ((nextrow < 0) || (nextrow >= 10) || (nextcol < 0) || (nextcol >= 10)) {
return false;
}
if (walkgrid[nextrow][nextcol] == '.') continue; /* try next */
walkgrid[nextrow][nextcol] = alpha++;
} while (false);
Or we could rewrite those last three lines as:
} while (walkgrid[nextrow][nextcol] == '.');
walkgrid[nextrow][nextcol] = alpha++;

Changing value in rectangular two dimensional array

I am creating a very rudimentary battle ship program for fun and I
have come across a problem with changing values in my rectangular two dimensional array. Essentially, there are five "ships" placed in this two dimensional array. A user then inputs an integer to see if they hit or miss. I wanted the output to display the array with the guessed number represented with an X for a miss and a 0 for a hit. I am having trouble with changing the value at area[i][j] when it equals the value of t to the 0 or X. I am new to java so I am trying to learn. Any help would be appreciated. Thank you in advance.
import java.util.*;
public class battleship {
//Rudimentary Battleship game
public static void main(String[] args) {
System.out.println(" Hello and welcome to a basic version of Battleship.");
System.out.println(" The objective of this game is to sink all five ships located on the grid listed below.");
System.out.println(" Follow the prompt located underneath the grid ");
final int ROWS = 10;
final int COLS = 10;
int sum = 0;
int [][] area = { {1,2,3,4,5,6,7,8,9,10},
{11,12,13,14,15,16,17,18,19,20},
{21,22,23,24,25,26,27,28,29,30},
{31,32,33,34,35,36,37,38,39,40},
{41,42,43,44,45,46,47,48,49,50},
{51,52,53,54,55,56,57,58,59,60},
{61,62,63,64,65,66,67,68,69,70},
{71,72,73,74,75,76,77,78,79,80},
{81,82,83,84,85,86,87,88,89,90},
{91,92,93,94,95,96,97,98,99,100} };
for(int i=0; i < area.length; i++) {
for (int j=0; j < area[i].length; j++) {
if(area[i][j] < 10)
System.out.print(" "+(area[i][j])+" ");
else if(area[i][j] < 100)
System.out.print(" "+(area[i][j])+" ");
else
System.out.print(" "+(area[i][j])+" ");
}
System.out.println("");
}
Scanner input = new Scanner(System.in);{
System.out.println("Enter attack integer:");
int t;
while(true){
t = input.nextInt();
if ((t == 41) || (t == 42) || (t == 43)){
System.out.println("Hit - Destroyer");}
if ((t == 80) || (t == 90) || (t == 100)){
System.out.println("Hit - Submarine");}
if((t == 52) || (t == 62) || (t== 72) || (t == 82) || (t == 92)){
System.out.println ("Hit - Aircraft Carrier");}
if((t == 15) || (t == 16) || (t == 17) || (t == 18)){
System.out.println ("Hit - Battleship");}
if((t == 1) || (t == 2)){
System.out.println ("Hit - PT Boat");}
else{
System.out.println ("Miss");
}
System.out.println("You have fired at:" + t);
int w = 0;
for(int i=0; i < area.length; i++) {
for (int j=0; j < area[i].length; j++) {
if (area[i][j] == t)
if(area[i][j] < 10)
System.out.print(" "+(area[i][j])+" ");
else if(area[i][j] < 100)
System.out.print(" "+(area[i][j])+" ");
else
System.out.print(" "+(area[i][j])+" ");
}
System.out.println("");
}
}
}
}
}
You would be much better off using object orientation. Here's a skeleton to get you started:
public class Cell {
private boolean ship = false;
private boolean hit = false;
public boolean getHit() {
return hit;
}
public void setHit(boolean hit) {
this.hit = hit;
}
}
Then
public class Board() {
public static final int SIZE = 10;
private Cell[][] board;
public Board() {
board = new Cell[SIZE][SIZE];
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
board[i][j] = new Cell();
public boolean getHit(int x, int y) {
if(x < 0 || x >= SIZE || y < 0 || y >= SIZE) throw new BattleshipException("You queried a cell that doesn't exist!");
return board[x][y].getHit();
}
// etc etc.
}
Flesh out all the methods you need, add fields when you need them, this will work much better!
This is simple, modifying your code:
if ((t == 41) || (t == 42) || (t == 43)){
System.out.println("Hit - Destroyer");
area[i][j] = "X";
}
if ((t == 80) || (t == 90) || (t == 100)){
System.out.println("Hit - Submarine");
area[i][j] = "X";
}
if((t == 52) || (t == 62) || (t== 72) || (t == 82) || (t == 92)){
System.out.println ("Hit - Aircraft Carrier");
area[i][j] = "X";
}
if((t == 15) || (t == 16) || (t == 17) || (t == 18)){
System.out.println ("Hit - Battleship");
area[i][j] = "X";
}
if((t == 1) || (t == 2)){
System.out.println ("Hit - PT Boat");
area[i][j] = "X";
}
else{
System.out.println ("Miss");
area[i][j] = "O";
}
A note: be careful, arrays are 0 indexed, so your ship positions don't exactly correspond to the way you set up the grid. i.e. area[4][1] is not "41". You seemed to do this correctly (in the case of the destroyer) for the columns but not the rows. The if statements should check for 31, 32, 33 if the ship is at area[4][0], area[4][1], area [4][2]. In fact, you might be better off labeling the positions from 00, 01, 02, ... , 97, 98, 99 so that the indices correspond to the numbers.

Categories

Resources