I have a string (replacedLigning) containing y=3-2+4x-6. I want xVærdi (an ArrayList) to contain the x value. In the example y=3-2+4x-6 I want the xVærdi to store "4", since that's how many x'es there are. The initial value of xVærdi is none, and the problem is, that substring isn't able to find the "x", so the xVærdi will not contain any elements. Or so I think.
the i is initialized as 1
while(isNumber(replacedLigning.substring((replacedLigning.indexOf("x")-i),(replacedLigning.indexOf("x")-i+1))) == true){
xVærdi.add(replacedLigning.substring((replacedLigning.indexOf("x")-i),(replacedLigning.indexOf("x")-i+1)));
i++;
}
And
System.out.println(xVærdi); //It doesn't contain anything. Output: []
The isNumber method:
public static boolean isNumber(String str) {
if((str.equals("-") && fortegn == false)){
fortegn = true; //fortegn is a variable that allows the number to have it's minus with it
return true;
}
else if (str.equals("+") || str.equals("*") || str.equals("/") || str.equals("=")){
return false;
} else if((str.equals(".") && !fortegn) || (str.equals("0") && !fortegn) || (str.equals("1") && !fortegn) || (str.equals("2") && !fortegn) || (str.equals("3") && !fortegn) || (str.equals("4") && !fortegn) ||
(str.equals("5") && !fortegn) || (str.equals("6") && !fortegn) || (str.equals("7") && !fortegn) || (str.equals("8") && !fortegn) || (str.equals("9") && !fortegn)){
return true;
} else
return false;
}
EDIT:
I have made a mini-program, as you can see below. However, the error does not occur in this example, so I am at a loss why it is happening. So I'm uploading a bigger part of my program. My output is 4, which is intended, and occurs.
import java.util.*;
import java.lang.*;
public class Eksempel {
private static boolean fortegn = false;
private static int i = 1;
static ArrayList xVærdi = new ArrayList();
private static String ligning = "y=3-2+4x-6";
public static boolean erTal(String str) {
if((str.equals("-") && fortegn == false)){ //Variablen 'fortegn' sørger for at inkludere fortegnet af et tal, selvom det ikke er et tal. Dette sker kun en gang.
fortegn = true;
return true;
}
else if (str.equals("+") || str.equals("*") || str.equals("/") || str.equals("=")){
return false;
} else if((str.equals(".") && !fortegn) || (str.equals("0") && !fortegn) || (str.equals("1") && !fortegn) || (str.equals("2") && !fortegn) || (str.equals("3") && !fortegn) || (str.equals("4") && !fortegn) ||
(str.equals("5") && !fortegn) || (str.equals("6") && !fortegn) || (str.equals("7") && !fortegn) || (str.equals("8") && !fortegn) || (str.equals("9") && !fortegn)){
return true;
} else //Kommer kun så langt hvis klienten har indtastet et bogstav andet end x.
return false;
}
public static void main(String[] args) {
while(erTal(ligning.substring((ligning.indexOf("x")-i),(ligning.indexOf("x")-i+1))) == true){
xVærdi.add(ligning.substring((ligning.indexOf("x")-i),(ligning.indexOf("x")-i+1)));
i++;
}
Collections.reverse(xVærdi);
double xResult = Double.parseDouble(String.join("", xVærdi));
System.out.println(xResult); //returns 4.0 which it should
}}
The longer code that doesn't work:
import java.util.*;
import java.lang.*;
public class Server{
private static String ligning = y=3x^3-2x^2+4x-6;
private static String replacedLigning;
private static int i = 1;
static ArrayList xVærdi = new ArrayList();
static ArrayList x2Værdi = new ArrayList();
static ArrayList x3Værdi = new ArrayList();
while(erTal(ligning.substring((ligning.indexOf("x^3")-i),
(ligning.indexOf("x^3")-i+1))) == true){
x3Værdi.add(ligning.substring((ligning.indexOf("x^3")-i),
(ligning.indexOf("x^3")-i+1)));
i++;
}
replacedLigning = ligning.replace("x^3","");
while(erTal(replacedLigning.substring((replacedLigning.indexOf("x^2")-i),(replacedLigning.indexOf("x^2")-i+1))) == true){
x2Værdi.add(replacedLigning.substring((replacedLigning.indexOf("x^2")-i),(replacedLigning.indexOf("x^2")-i+1)));
i++;
}
System.out.println(replacedLigning); //gives: y=3-2x^2+4x-6
replacedLigning = replacedLigning.replace("x^2","");
System.out.println(replacedLigning); //gives y=3-2+4x-6
i=1;
while(erTal(replacedLigning.substring((replacedLigning.indexOf("x")-i),(replacedLigning.indexOf("x")-i+1))) == true){
xVærdi.add(replacedLigning.substring((replacedLigning.indexOf("x")-i),(replacedLigning.indexOf("x")-i+1)));
i++;
}
Collections.reverse(xVærdi);
Collections.reverse(x2Værdi);
Collections.reverse(x3Værdi);
System.out.println(xVærdi); **//Contains nothing: [] should contain [4]**
System.out.println(x2Værdi); **//Contains nothing: [] should contain [-2]**
System.out.println(x3Værdi); **//Contains [4, ., 6, -] should contain [3]**
double xResult = Double.parseDouble(String.join("", xVærdi)); //gets an error, because the arraylist is empty.
double x2Result = Double.parseDouble(String.join("", x2Værdi));
double x3Result = Double.parseDouble(String.join("", x3Værdi));
Related
I am trying to check if a user has inputted a double between 3.5 and 7. I have tried to use the actual double and Math.round();, as well as StrictMath.round(). I have also tried to parse the string inputted as a float but it didn't change anything. Here is the basic code I used:
import java.util.Scanner;
public class IfStatement {
public static void main(String[] args) {
//create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter first double: ");
double number = input.nextDouble();
if (isDouble(number)==true) {
double x = Double.parseDouble(number);
if (3.5 <= x <= 7) {
System.out.println("good");
} else {
System.out.println("incorrect input");
}
} else {
System.out.println("incorroct input");
}
}
public static booleen isDouble(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
++i;
}
int integerPartSize = 0;
int exponentPartSize = -1;
while (i < length) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
if (c == '.' && integerPartSize > 0 && exponentPartSize == -1) {
exponentPartSize = 0;
} else {
return false;
}
} else if (exponentPartSize > -1) {
++exponentPartSize;
} else {
++integerPartSize;
}
++i;
}
if ((str.charAt(0) == '0' && i > 1 && exponentPartSize < 1)
|| exponentPartSize == 0 || (str.charAt(length - 1) == '.')) {
return false;
}
return true;
}
}
I have also tried making 3.5 3 in the if statement but got no dice. I just need a loose explanation and not a full solution.
I've edited your code.
boolean spelling
isDouble() takes a String
a <= x <= b chained expressions are not allowed in Java
Also,
if ((str.charAt(0) == '0' && i > 1 && exponentPartSize < 1) || exponentPartSize == 0 || (str.charAt(length - 1) == '.')) {
return false;
}
return true;
can be simplified to
return (str.charAt(0) != '0' || i <= 1 || exponentPartSize >= 1)
&& exponentPartSize != 0 && (str.charAt(length - 1) != '.');
Here's the full code.
class Test {
public static boolean isDouble(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
++i;
}
int integerPartSize = 0;
int exponentPartSize = -1;
while (i < length) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
if (c == '.' && integerPartSize > 0 && exponentPartSize == -1) {
exponentPartSize = 0;
} else {
return false;
}
} else if (exponentPartSize > -1) {
++exponentPartSize;
} else {
++integerPartSize;
}
++i;
}
return (str.charAt(0) != '0' || i <= 1 || exponentPartSize >= 1)
&& exponentPartSize != 0 && (str.charAt(length - 1) != '.');
}
public static void main(String[] args) {
//create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter first double: ");
String number = input.nextLine();
if (isDouble(number)) {
double x = Double.parseDouble(number);
if (3.5 <= x && x <= 7) {
System.out.println("good");
} else {
System.out.println("incorrect input");
}
} else {
System.out.println("incorroct input");
}
}
}
I have an assignment where there is a combination lock box that has a 4-letter word as the combination, and a player has to try to guess the combination by guessing the word one letter at a time. For each round, a clue should be outputted to show how close a person's guess is to the actual word. If the letter in the guess is also in the same position in the combination lock, then the matching letter is outputted. If the letter is in the word but not in the same position, a + is outputted, and when the letter is not present in the word at all, an * is outputted. All of those characters are added to a single string to show the result.
I've tried to code all of this in Java, but it returns an incorrect result with a null before it. Can someone help me fix these issues?
public class CombinationLock
{
private String lock;
private String guess;
private String guessLetter1;
private String guessLetter2;
private String guessLetter3;
private String guessLetter4;
private String lockLetter1;
private String lockLetter2;
private String lockLetter3;
private String lockLetter4;
private String modifiedGuess;
private char combinationLetter;
private char guessLetter;
public CombinationLock(String newLock)
{
lock = newLock;
}
public String getClue(String newGuess)
{
guess = newGuess;
for(int i = 0; i < lock.length(); i++)
{
combinationLetter = lock.charAt(i);
guessLetter = guess.charAt(i);
if(i == 0)
{
lockLetter1 += combinationLetter;
guessLetter1 += guessLetter;
}
else if(i == 1)
{
lockLetter2 += combinationLetter;
guessLetter2 += guessLetter;
}
else if(i == 2)
{
lockLetter3 += combinationLetter;
guessLetter3 += guessLetter;
}
else if(i == 3)
{
lockLetter4 += combinationLetter;
guessLetter4 += guessLetter;
}
if(combinationLetter == guessLetter)
{
modifiedGuess += combinationLetter;
}
else if(guessLetter1 == lockLetter1 || guessLetter1 == lockLetter2 || guessLetter1 == lockLetter3 || guessLetter1 == lockLetter4)
{
modifiedGuess += '+';
}
else if(guessLetter2 == lockLetter1 || guessLetter2 == lockLetter2 || guessLetter2 == lockLetter3 || guessLetter2 == lockLetter4)
{
modifiedGuess += '+';
}
else if(guessLetter3 == lockLetter1 || guessLetter3 == lockLetter2 || guessLetter3 == lockLetter3 || guessLetter3 == lockLetter4)
{
modifiedGuess += '+';
}
else if(guessLetter4 == lockLetter1 || guessLetter4 == lockLetter2 || guessLetter4 == lockLetter3 || guessLetter4 == lockLetter4)
{
modifiedGuess += '+';
}
else
{
modifiedGuess += '*';
}
}
return modifiedGuess;
}
}
public class MyProgram extends ConsoleProgram
{
public void run()
{
CombinationLock c1 = new CombinationLock("bird");
System.out.println(c1.getClue("barn"));
}
}
You need to initialise your modifiedGuess variable, i.e.
public CombinationLock(String newLock)
{
lock = newLock;
modifiedGuess = "";
}
Alternatively, you can look into StringUtils.difference function which may give you a similar result (if allowed for the assignment).
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#difference(java.lang.String,%20java.lang.String)
I would like to evaluate a phone number using the provided method. The phone number should always have a length of 10. However the following method always seems to return false. Why is that? Thanks.
public static boolean valPhoneNumber(String phonenumber){
boolean result= true;
if (phonenumber.length() > 10 || phonenumber.length() < 10){
result= false;
}else
phonenumber.length();
char a=phonenumber.charAt(0);
char b=phonenumber.charAt(1);
char d=phonenumber.charAt(3);
char e=phonenumber.charAt(4);
char f=phonenumber.charAt(5);
if (a<2 || a>9){
result = false;
}else if( b<0 || b>8){
result = false;
}else if (d<2 || d>9){
result = false;
}else if (e==1 && f==1){
result = false;
}
return result;
}
So looking into your ladder which is comparing character to number. In this case the comparison will happen with ASCII value.
You can put single quotes to check the range:
if (a < '2' || a > '9') {
result = false;
} else if( b < '0' || b > '8') {
result = false;
} else if (d < '2' || d > '9') {
result = false;
} else if (e == '1' && f == '1') {
result = false;
}
One liner:
result = !((a < '2' || a > '9') || (b < '0' || b > '8') || (d < '2' || d > '9') || (e == '1' && f == '1'));
I think your code wrong at the parsing phonenumber.charAt(). This always return char, and when you do comparision with integer it will convert to number which present to that char code (ASCII code). I think you should modify your code to int a=Character.getNumericValue(phonenumber.charAt(0)); and so on
I think an approach with regex here would be the cleanest and easiest solution.
public static boolean valPhoneNumber(String phonenumber){
String regex = "[2-9][0-8][0-9][2-9][02-9][0-29][0-9]{4}";
return phonenumber.matches(regex);
}
You should cast the char variables to integer.
you can try this:
int a = Integer.parseInt(phonenumber.substring(0,1));
I added single quotes to check the range. Thank you all.
public static boolean valPhoneNumber(String phonenumber) {
boolean result= true;
if (phonenumber.length() != 10) {
result = false;
} else {
//phonenumber.length();
char a = phonenumber.charAt(0);
char b = phonenumber.charAt(1);
char d = phonenumber.charAt(3);
char e = phonenumber.charAt(4);
char f = phonenumber.charAt(5);
if (a < '2' || a > '9') {
} else if( b<'0' || b>'8') {
result = false;
} else if (d < '2' || d > '9') {
result = false;
} else if (e == '1' && f == '1') {
result = false;
}
}
return result;
}
I have to create the yahtzee game and its methods like full house, small straight, big straight, 3 of kind, 4 of kind , and chance. Now this is what i have done so far and i would like to know if my methods are right and also i'm having a hard time trying to figure out how to check if its yahtzee , 3 of kind, 4 of kind , etc and this is in my main method. The program consists of seven rolls, where every roll can have up to two sub-rolls
static final int NUM_RERROLS_ = 2;
static final int NUM_OF_DICE = 5;
static final int NUM_ROLLS_ = 7;
static final int[] dice = new int[NUM_OF_DICE];
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
rollDice();
for (int i = 0; i < NUM_RERROLS_; i++) {
if (gotYatzee()) {
break;
}
System.out.println(diceToString());
askUser();
System.out.println("Which dice do you want to reroll: ");
secondReroll(convert(keyboard.nextLine()));
}
System.out.println(diceToString());
if (gotYatzee()) {
System.out.println("You got Yatzee & 50 points!");
} else if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
{
System.out.println("SORRY NO YAHTZEE");
}
if (askUser() == false) {
if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
}
}
public static void rollDice() {
for (int i = 0; i < NUM_OF_DICE; i++) {
dice[i] = randomValue();
}
}
public static int randomValue() {
return (int) (Math.random() * 6 + 1);
}
public static String diceToString() {
String dado = "Here are your dice: ";
for (int element : dice) {
dado = dado + element + " ";
}
return dado;
}
public static boolean gotYatzee() {
for (int element : dice) {
if (element != dice[0]) {
return false;
}
}
return true;
}
public static void secondReroll(int[] newValue) {
for (int element : newValue) {
dice[element - 1] = randomValue();
}
}
public static int[] convert(String s) {
StringTokenizer st = new StringTokenizer(s);
int[] a = new int[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
a[i++] = Integer.parseInt(st.nextToken());
}
return a;
}
public static boolean Chance() {
for (int element : dice) {
int i = 0;
if (element != dice[i]) {
i++;
return false;
}
}
return true;
}
public static boolean smallStraight() {
for (int i = 1; i <= NUM_OF_DICE; i++) {
boolean b = false;
for (int j = 0; j < NUM_OF_DICE; j++) {
b = b || (dice[j] == i);
}
if (!b) {
return false;
}
}
return true;
}
public static boolean largeStraight() {
int[] i = new int[5];
i = dice;
sortArray(i);
if (((i[0] == 1) && (i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5))
|| ((i[0] == 2) && (i[1] == 3) && (i[2] == 4) && (i[3] == 5) && (i[4] == 6))
|| ((i[1] == 1) && (i[2] == 2) && (i[3] == 3) && (i[4] == 4) && (i[5] == 5))
|| ((i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5) && (i[5] == 6))) {
return true;
} else {
return false;
}
}
public static boolean askUser() {
Scanner keyboard = new Scanner(System.in);
int a = 0;
String yes = "Yes";
String no = "No";
System.out.println("Do you want to reroll the dice again: Yes or No? ");
String userInput;
userInput = keyboard.next();
if (userInput.equals(yes)) {
System.out.println("ALRIGHTY!!");
return true;
} else if (userInput.equals(no)) {
}
return false;
}
public static boolean threeKind() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) // Three of a Kind
|| ((a[1] == a[2]) && ((a[2] == a[3])
|| (((a[2] == a[3]) && (a[3] == a[4]))))))) {
return true;
} else {
return false;
}
}
/*public static boolean fourKind(int[] dice) {
}
*/
public static int[] sortArray(int[] numbers) {
int stop;
for (stop = 0; stop < numbers.length; stop++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
swap(numbers, i, i + 1);
}
}
}
return numbers;
}
public static void swap(int[] numbers, int pos1, int pos2) {
int temp = numbers[pos1];
numbers[pos1] = numbers[pos2];
numbers[pos2] = temp;
}
public static boolean fullHouse() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) && // Three of a Kind
(a[3] == a[4]) && // Two of a Kind
(a[2] != a[3]))
|| ((a[0] == a[1]) && // Two of a Kind
((a[2] == a[3]) && (a[3] == a[4])) && // Three of a Kind
(a[1] != a[2]))) {
return true;
} else {
return false;
}
}
}
basically i want to figure out a way to check if its full house, 3 of kind, 4 of kind , etc
You have 6 dice after three rolls. Sort the array of user-retained dice after the 3 rolls.
Yahtzee: ((die[0] == die[4]) || (die[1] == die[5]))
4 of a kind: ((die[0] == die[3]) || (die[1] == die[4] || (die[2] == die[5]))
Small straight, 3 tests (x = 3,4,5): ((die[x] - die[x-3]) == 3)
Large straight, 2 tests (x = 4,5): ((die[x] - die[x-4]) == 4)
etc.
Chance: Up to the user, right?
Unless I'm missing something (I'm a little rusty on Yatzee), this should be fairly straightforward.
another question to put out there. I was working on an assignment to create hash functions and all that jazz, and i have stumbled across a small problem.
Line 35:21, where it reads arrpos += prearrpo & ______,
in my head works... What im trying to do is access arr.length from the HashTable() method. I've read around, suggestions with needing to creat an object of size arr.length; however in my mind, this seems overly complicated-
Is there another way i can access the variable in the HashTable method, but inside the insert method?
Another not so important question involves the giant block of if() statements in the letter(char c) class; im certain there must be a shorter way of doing this... I would have initially used the ascii values; but the specifications were quite particular about using the values 1-26 for lower/upper case letters-
Thanks
import java.io.*;
public class HashTable {
public HashTable() {
//Create an array of size 101
String arr[] = new String[101];
//System.out.println("Size1: ");
}
public HashTable(int tsize) {
int size = 2 * tsize;
//System.out.println("Size: " + size);
boolean isPrime = checkPrime(size);
//System.out.println("IsPrime: " + isPrime);
while (isPrime == false) {
//System.out.println("Size: " + size);
size++;
isPrime = checkPrime(size);
}
//System.out.println("Size: " + size);
String arr[] = new String[size];
}
public boolean insert(String line) {
String str = line;
char[] ch = str.toCharArray();
int slen = str.length();
int arrpos = 0;
int hash = slen;
for (int i = 0; i < slen; i++) {
double prearrpo = letter(ch[i]) * Math.pow(32, (hash - 1));
arrpos += prearrpo % arr.length();
hash--;
}
System.out.println(arrpos);
System.out.println("array size:");
System.out.println();
return false;
}
private int letter(char c) {
char ch = c;
if (ch == 'A' || ch == 'a') {
return 1;
}
if (ch == 'B' || ch == 'b') {
return 2;
}
if (ch == 'C' || ch == 'c') {
return 3;
}
if (ch == 'D' || ch == 'd') {
return 4;
}
if (ch == 'E' || ch == 'e') {
return 5;
}
if (ch == 'F' || ch == 'f') {
return 6;
}
if (ch == 'G' || ch == 'g') {
return 7;
}
if (ch == 'H' || ch == 'h') {
return 8;
}
if (ch == 'I' || ch == 'i') {
return 9;
}
if (ch == 'J' || ch == 'j') {
return 10;
}
if (ch == 'K' || ch == 'k') {
return 11;
}
if (ch == 'L' || ch == 'l') {
return 12;
}
if (ch == 'M' || ch == 'm') {
return 13;
}
if (ch == 'N' || ch == 'n') {
return 14;
}
if (ch == 'O' || ch == 'o') {
return 15;
}
if (ch == 'P' || ch == 'p') {
return 16;
}
if (ch == 'Q' || ch == 'q') {
return 17;
}
if (ch == 'R' || ch == 'r') {
return 18;
}
if (ch == 'S' || ch == 's') {
return 19;
}
if (ch == 'T' || ch == 't') {
return 20;
}
if (ch == 'U' || ch == 'u') {
return 21;
}
if (ch == 'V' || ch == 'v') {
return 22;
}
if (ch == 'W' || ch == 'w') {
return 23;
}
if (ch == 'X' || ch == 'x') {
return 24;
}
if (ch == 'Y' || ch == 'y') {
return 25;
}
if (ch == 'Z' || ch == 'z') {
return 26;
}
return 0;
}
public boolean lookUp(String string) {
//
return false;
}
public String getNum() {
//
return null;
}
public int length() {
return 0;
}
private static boolean checkPrime(int size) {
if (size % 2 == 0) {
return false;
}
double c = Math.sqrt(size);
for (int i = 3; i < c; i += 2) {
if (size % i == 0) {
return false;
}
}
return true;
}
}
public HashTable() is a constructor. Your arr[] should actually be a private member of your class and you should initialize it in all constructors or make sure you never access without intializing it.
public class HashTable {
private String[] arr;
public HashTable()
{
//Create an array of size 101
arr[] = new String[101];
System.out.println("Size1: ");
}
etc...
Since it seems that your implementation is array backed, you need to declare the array as a member variable:
public class HashTable {
String arr[] = null;
And then initialize it in your constructors ( note in Java world methods like HashTable() is called a constructor) as :
arr = new String[whatever_size];