Java - Looping Number Strings - java

You all were so helpful yesterday in getting over my first hump in this problem that I wanted to see if there's a way I can modify my final product (Apologies if my formatting is off - Still trying to get indentations correct in my IDE.
import javax.swing.JOptionPane;
public class NumberLoops {
public static void main(String[] args) {
String strNum1;
String strNum2;
int intNum;
boolean isValid = true;
boolean isError = false;
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
JOptionPane.showMessageDialog(null, "Negative Digit Found - Enter Positive Numbers Only", "Error", JOptionPane.INFORMATION_MESSAGE);
isValid = false;
break;
}
}
if (isValid){
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
intNum = Character.getNumericValue(c);{
if (intNum > 0 && intNum <= 9){
isError = true;
break;
}
}
}
}
if (isError){
int aDigit,totalNum=0;
char chDigit;
strNum2 = String.valueOf(strNum1);
for (int count=0; count<strNum1.length();count++){
chDigit = strNum2.charAt(count);
aDigit = Character.getNumericValue(chDigit);
totalNum += aDigit;
if (aDigit > 0 && aDigit <= 9){
System.out.print(aDigit + " ");
}
}
System.out.print(" " + "The sum is: " + totalNum);
}
}
}
My question concerns the last loop. It functions as desired by printing to the console if I enter say 123123 into the message prompt, it lists that string as 1 2 3 1 2 3 and then the total of 12.
But that is in the console itself. What I'm trying to wrap my mind around is getting it to display in a message box instead of the console.
I'm guessing I need to create a new string like (incoming pseudocode):
if (aDigit > 0 && aDigit <= 9){
strNum3 = everycharinStr2 + " "
Which is the part I guess I'm not grasping.
FYI, this is a homework assignment so I don't necessarily want an outright answer, but I feel I am so close that I need some extra eyes on it to see if there's anything I can do. (I have read up on arrays and such but we aren't at that point yet so I don't think I'll go down that road quite yet.)

You only have to make a little change in your code:
strNum2 = String.valueOf(strNum1);
String resultString = "";
for (int count=0; count<strNum1.length();count++){
chDigit = strNum2.charAt(count);
aDigit = Character.getNumericValue(chDigit);
totalNum += aDigit;
if (aDigit > 0 && aDigit <= 9){
System.out.print(aDigit + " ");
resultString += aDigit + " ";
}
}
JOptionPane.showMessageDialog(null, resultString);
Create a new String and in each iteration append the number to this String, then show it in a dialog.

The errors are commented out.
//if (intNum > 0 && intNum <= 9){
if (intNum < 0 || intNum > 9){
isError = true;
break;
}
//if (aDigit > 0 && aDigit <= 9){
if (aDigit >= 0 && aDigit <= 9){
System.out.print(aDigit + " ");
//resultString+ = aDigit + " ";
resultString += "" + aDigit;
}
//if (isError) {
if (!isError) {

Just use a JLabel!
Since your already using swing, this would be your best choice. But then you'd need a frame and panel, so if you don't already have that, don't do this.
JLabel label = new JLabel()
label.setText("Random Text!")
You can also do this, with a pop up:
JOptionPane.showMessageDialog(null, "My String!");

Related

java.util.NoSuchElementException: No line found. Works before, but not later. I don't know why

I'm trying to make a game, and for whatever reason the Scanner works before in a separate method, but not in this one.
Works in:
Scanner in = new Scanner(System.in); // Scanner in case of invalid input
for (int i = 1; i <= p.getSpeed(); i++) { // loop to account for invalid direction
if (d.equalsIgnoreCase("right") || d.equalsIgnoreCase("r") && p.getX() <= width - 2) { // right
if (board[p.getY()][p.getX() + 1] == ' ') {
board[p.getY()][p.getX()] = ' ';
p.setX(p.getX() + 1);
board[p.getY()][p.getX()] = 'P';
}
else { // right not open
System.out.println("Please input a valid direction");
d = in.nextLine();
i--;
}
}
Doesn't work in:
Scanner in = new Scanner(System.in); // Scanner in case of invalid input
int i = 1;
while (i == 1) {
if (d.equalsIgnoreCase("right") || d.equalsIgnoreCase("r") && p.getX() <= width - 2) { // right
for (int j = 0; j <= numZombies - 1; j++) {
if (zombie[j].getX() == p.getX() + 1 && zombie[j].getY() == p.getY()) { // checks each zombie to see if it is one to the right of the player
zombie[j].subtractHealth(p.getAttack());
break;
}
if (zombie[j].getX() == p.getX() + 2 && zombie[j].getY() == p.getY()) {
zombie[j].subtractHealth(p.getAttack());
break;
}else if (j == numZombies - 1) { // if no zombies are found
System.out.println("There is no zombie there, please insert a new direction");
d = in.nextLine();
i--;
}
}
}
}
The methods all work and the logic is fine, I just don't know why it works for the first but not the second one
Closing the first scanner was the problem, getting rid of that code fixed it. Thanks Charles

Java battleship program not printing board correctly

I am having a problem with my java battleship program not printing the coordinates that the user enters. When the user guesses a spot on the board its supposed to update the space with an "X" if its a hit, if not then the board remains the same. But when a user guesses wrong on my program, it prints everything except the space where the user guessed. I believe that my else statement where the board updates is the problem, but any modification I did resulted in the board not printing anything.
import java.util.Random;
import java.util.Scanner;
class Battleship {
public static char randChar(){
final String alphabet = "ABCDE";
final int N = alphabet.length();
char rand;
Random r = new Random();
rand = alphabet.charAt(r.nextInt(N));
return rand;
}
public static void main (String[] args) throws java.lang.Exception {
char[] letters = {' ', 'A', 'B', 'C', 'D', 'E'};
int[] numbers ={1, 2, 3, 4, 5};
int[][] ships = new int[7][2];
char colGuess;
int rowGuess;
Boolean boardFlag=false;
Scanner scan = new Scanner(System.in);
//creates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
System.out.print(letters[j] + "" + numbers[i-1]);
}
System.out.print(" ");
}
System.out.println();
}
//assigns ships to random spots
assignShips(ships);
System.out.println("Enter your guess for the column:");
colGuess = scan.next().charAt(0);
//converts to uppercase
colGuess = Character.toUpperCase(colGuess);
System.out.println("Enter your guess for the row:");
rowGuess = scan.nextInt();
//shows player what they entered
System.out.println("you entered: " + (char) colGuess + rowGuess);
//calls method to check for a hit
fire(colGuess, rowGuess, ships);
boardFlag = fire(colGuess, rowGuess, ships);
System.out.println(boardFlag);
//updates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
if(letters[j] == colGuess && numbers[i - 1] == rowGuess) {
if(boardFlag==true) {
System.out.print(" " + "X");
}
}
else {
System.out.print(letters[j] + "" + numbers[i - 1]);
}
}
System.out.print(" ");
}
System.out.println();
}
}
public static void assignShips(int[][] ships) {
Random random = new Random();
for(int ship = 0; ship < 7; ship++) {
ships[ship][0] = randChar();
ships[ship][1] = random.nextInt(5);
//gives location of ships, for testing purposes
System.out.print("Ship:" + (ship+1)+ " is located at"+(char)ships[ship][0]+ships[ship][1]+"\n");
}
}
//checks user input to see if we have a hit
public static Boolean fire(char colGuess, int rowGuess, int[][] ships) {
Boolean hitFlag=false;
for(int ship = 0; ship < ships.length; ship++){
if(colGuess ==ships[ship][0] && rowGuess == ships[ship][1]){
hitFlag=true;
}
}
if(hitFlag == true) {
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
}
else {
System.out.println("sorry chief we missed em");
}
return hitFlag;
}
}
The reason its not showing up when you miss is because your net telling it to print anything.
if(letters[j] == colGuess && numbers[i-1] == rowGuess){
if(boardFlag==true) {
System.out.print(" "+"X");
}
}
Your only handling the coordinate the user input if they hit. To fix this you would need an else statement after your if(boardFlag == true)to handle printing if you miss.
The problem is in your update board portion of the code because you don't do anything if the guessed location isn't a hit.
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag) {
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
Full Update Portion:
//updates the board
for (int i = 0 ; i <= 5 ; i++){
for (int j = 0 ; j <= 5 ; j++){
if (i == 0) {
System.out.print(letters[j]+" ");
} else if (j == 0){
System.out.print(numbers[i-1] );
} else {
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag){
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
}
System.out.print(" ");
}
System.out.println();
}
This block (old version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em");
}
Should be (new version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em at " + (char)colGuess+rowGuess);
}
this will print:
sorry chief we missed em at D3 //D3 is a random possible set of coordinates
Rather than:
sorry chief we missed em //Old version
So all you have to add is (char)colGuess+rowGuess, which prints the coordinates of your previous guess.
Comment if you have any questions!

Using if statement to print whether a String is odd or even in java

public static void main(String[] args) {
Scanner String = new Scanner(System.in);
System.out.print("Enter a String: ");
String Str1 =String.nextLine();
String input;
input = Str1;
char[] inputArray = input.toCharArray();
String[] lines = new String[input.length() / 2 + 1];
int i, u;
for (i = 0; i < input.length() / 2; i++) {
char begChar = inputArray[i];
char endChar = inputArray[input.length() - i - 1];
int spacesBefore = i;
int spacesAfter = i;
int spacesInBetween = input.length() - 2 - 2 * i;
String line = "";
for (u = 0; u< spacesBefore; u++) {
line += " ";
}
line += begChar;
for (u = 0; u < spacesInBetween; u++) {
line += " ";
}
line += endChar;
lines[i] = line;
}
if (input.length() % 2 != 0) {
String lastLine = "";
for (u = 0; u < input.length() / 2; u++) {
lastLine += " ";
}
lastLine += inputArray[input.length() / 2];
lines[input.length() / 2] = lastLine;
}
for (i = 0; i < lines.length && lines[i] != null; i++) {
System.out.println(lines[i]);
}
System.out.print("String Length: ");
System.out.println(Str1.length());}
This is where I am having the issue with my code.
I am trying to get this to print whether the user entered String is odd or even. Using Netbeans IDE it keeps telling me that I have a bad operand type int for unary operator '!'. Everything else in the code is working like it should just can't get this to work.
if ( !(Str1.length( ) %0x2))
System.out.println("The String is odd");
else
System.out.println("The String is even");
! is an unary negation operator that expects a single boolean operand. Therefore it can't be applied on an int
You should change
if ( !(Str1.length( ) %0x2))
System.out.println("The String is odd");
else
System.out.println("The String is even");
To this
if (Str1.length() %2 != 0){
System.out.println("The String is odd");
}
else{
System.out.println("The String is even");
}
!= is the operator that checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
Basically you do this:
if (Str1.length() %2 != 0)
Currently you are attempting to call the ! operator on a integer result from using the % operator which is producing the error you are seeing currently
if (!(Str1.length( ) % 0x2))
System.out.println("The String is odd");
else
System.out.println("The String is even");
What you can do is what was suggested by others. This works because you are comparing your result of using the % operator with 2 which produces a boolean result. Therefore the if statement can evaluate it and determine it to be true or false. With the added ! operator you reverse the result of whatever the expression is inside the parentheses.
if (!(Str1.length( ) % 2 != 0))
System.out.println("The String is odd");
else
System.out.println("The String is even");

Adding a space inbetween a user inputed string

I want a user to enter a String and then add a space in between a character at a chosen interval.
example: user enters: hello
then asks for a space every 2 letters.
output = he_ll_o_
import java.util.Scanner;
public class stackOverflow {
public static void main(String[] args) {
System.out.println("enter a string");
Scanner input = new Scanner(System.in);
String getInput = input.nextLine();
System.out.println("how many spaces would you like?");
Scanner space = new Scanner(System.in);
int getSpace = space.nextInt();
String toInput2 = new String();
for(int i = 0; getInput.length() > i; i++){
if(getSpace == 0) {
toInput2 = toInput2 + getInput.charAt(i);
}
else if(i % getSpace == 0) {
toInput2 = toInput2 + getInput.charAt(i) + "_"; //this line im having trouble with.
}
}
System.out.println(toInput2);
}
}
Thats my code so far, it might be the completely wrong way of solving it, so correct me if im wrong. thanks in advance :)
I think you would want to formulate your loop body as follows:
for(int i = 0; getInput.length() > i; i++) {
if (i != 0 && i % getSpace == 0)
toInput2 = toInput2 + "_";
toInput2 = toInput2 + getInput.charAt(i);
}
But, there's a simpler way, using regular expressions:
"helloworld".replaceAll(".{3}", "$0_") // "hel_low_orl_d"
You can simplify your case distinction to:
toInput2 += getInput.charAt(i);
if(i != 0 && i % getSpace == 0) {
toInput2 += "_";
}
You should also think about renaming your variables.

Checking for user input to be only integers in Java

I'm doing lottery game for my assignment (user inputs 6 number, i will generate 8 unique winning numbers and 2 last numbers are supplementary). I need help with user input checking if input numbers are from 1 to 45 and input must be int, when input is not integer it throws an error.
This programming way is procedure way, how can i change it into object oriented way? I know that I must make methods in another java file and then link it back to this main. Can you suggest me how to do it?
I have tried try and catch, if and else (for input check) but i don't know how to check user input when it's in array. Thank you for help.
Here is my code:
class Lottery {
public static void main ( String[] args ) {
System.out.println("\nWelcome to the Lottery game.");
System.out.println("You can enter numbers from 1 to 45.");
// User input into an array
int[] input = new int[6];
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease enter your 6 lucky numbers: ");
for(int j = 0; j < 6; j++) {
input[j]=scanner.nextInt();
}
int check = scanner.nextInt();
if(check < 0 && check > 45) {
System.out.println("\nERROR: Please enter only numbers from 1 to 45!");
}
// Printing out unique winning numbers from random generator
System.out.println("\nWinning numbers: ");
MultiRandomGenerator mrg = new MultiRandomGenerator();
int[] set;
set = mrg.getSet();
for (int i = 0; i < set.length; i++) {
System.out.print(set[i] + " ");
}
// Loops for counting how many numbers user has guessed right
int count = 0; // for 6 numbers
int scount = 0; // for 2 last supplementary numbers
for(int i = 0; i < input.length; i++) {
for(int k = 0; k < set.length; k++) {
if (k < 6) {
if (set[k] == input[i]) {
count++;
} else {
if (set[k] == input[i]) {
scount++;
}
}
}
}
}
System.out.print("\n\nYou guessed right " + count + " winning numbers.");
System.out.print("\nYou guessed right " + scount + " suplementary numbers.");
// If statments for printing out winning prizes
if (count == 6) {
System.out.println("\nYou have won 1st price!");
} if (count == 5 && scount == 1) {
System.out.println("\nYou have won 2st price!");
} if (count == 5) {
System.out.println("\nYou have won 3st price!");
} if (count == 4) {
System.out.println("\nYou have won 4st price!");
} if (count == 3 && scount == 1) {
System.out.println("\nYou have won 5st price!");
} if (count == 1 && scount == 2) {
System.out.println("\nYou have won 6st price!");
} else {
System.out.println("\nSorry, you didn't won anything.");
}
}
}
Sample code to go through array and find the invalid user input.
set = mrg.getSet();
String[] userDataStatus = new String[45];
for (int i = 0; i < set.length; i++)
{
try
{
String inputdata = set.get(i);
if(inputdata != null && inputdata.trim().length() > 0)
{
int currentNumber = Integer.parseInt(userdata);
userDataStatus[i] = "Y";//Y represent valid number
}
}
catch (NumberFormatException ex )
{
userDataStatus[i] = "N";//If it throws exception then save as 'N'
}
}
Use the above String array and display error messaage to users.
You can check in your loop, something like
int val;
try
{
input[j] = Integer.parseInt( scanner.nextString() );
}
catch (NumberFormatException ex )
{
}

Categories