How to multiply different indexes by different values? - java

I am creating a scrabble game, where the characters get the same values as scrabble,(q & z =10),(k=5), etc, and the main issue that I am having is that I am asking the user to input 2 ints after the word, the first being the index of the bonus tile, and the second being the multiplier to multiply the word with. The value without the multiplier is correct, but the multiplier is not working.
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String word = kb.next();
int bonusI = kb.nextInt();
int bonusMult = kb.nextInt();
int score=0;
for (int i=0; i<word.length();i++){
int letterScore;
String letter=word.substring(i,i+1);
if (letter.equals("d")||letter.equals("g")){
letterScore=2;
}
else if (letter.equals("k")) {
letterScore=5;
}
else if (letter.equals("j")||letter.equals("x")){
letterScore=8;
}
else if (letter.equals("q")||letter.equals("z")) {
letterScore=10;
}
else {
letterScore=1;
}
for (int j=0;j<1;j++){
if (word.substring(i,i+1).equals(bonusI)){
letterScore*=bonusMult;
}
}
score+=letterScore;
}
System.out.println(score);
}
}
For example, if the input is dog 2 3 then the correct output would be 9,(d is 2 points,o according to scrabble is 1 point, and g is 2 points, but since the 1st int inputted was 2, and g has an index of 2, it is then multiplied by the bonus of 3, which makes g=6, adding them 2+1+6=9) but instead my output is 5 because the multiplier for g is not working.

Looks like you have a mistake here.
word.substring(i,i+1).equals(bonusI)
word.substring(i,i+1) is String and gives one letter
bonusI is an int and tives one number
This will never be true

if (word.substring(i,i+1).equals(bonusI)) - This condition will be always false as you can't compare a string with int value.
Instead you can just replace the internal for loop with below code
if (bonusI == i)
{
letterScore*=bonusMult;
}

Related

Array in java, how to calculate hamming distance between String and int?

I have to write a programm.I am learning 2 month java and i am stuck.An advice how to forwoard on this is very helful for me.
The class will contain two methods, public static void main and public static int hamming.
The hamming method will accept two alphanumeric parameters and return an integer
number which is the Hamming distance of these two alphanumerics. For example, if as
given arguments “dog” and “dig” the method will return the integer 1, which is the distance
Hamming between them. In the event that the arguments do not have the same length, the method will
returns -1.
The main method will include as local variables an array of alphanumerics with 5 elements
and name stringList and an array of integers with 5 elements and name distances. main will execute them
following actions:
• It will read an extra alphanumeric, which it will store in a local variable with
target name.
• In an iterative process, it will calculate (by calling the hamming method) the distances
of the alphanumeric array stringList from the target and will store them in the corresponding ones
positions of the distances table (it will be either integer >=0 or -1 if n is not applied
distance due to different length).
• After the calculations it will go through the distances table and find the shortest one
distance that he includes. Of course, the value -1 will not be calculated.
• It will display (all) the contents of the distances table on the screen, as well as the
alphanumeric array stringList with the shortest distance from the target. If they exist
more than one case, it will display one.
Your program's screen output will look like the following samples
execution:
Example 1:
Enter string: dog
Enter string: cat
Enter string: jim
Enter string: bed
Enter string: toe
Enter target: house
Contents of array distances
0 -1
1 -1
2 -1
3 -1
4 -1
No Hamming distance found
Example 2:
Enter string: dog
Enter string: cat
Enter string: jim
Enter string: bed
Enter string: blackboard
Enter target: bid
Contents of array distances
0 3
1 3
2 2
3 1
4 -1
String with min Hamming distance: bed.
public class Thema3
{
public static void main (String[]args){
//Creating scanner object
Scanner stringList = new Scanner(System.in);
// creating String array of 5
String [] stringList1 = new String[6];
double[] targetString= {};
stringList1[1]="";
stringList1[2]="";
stringList1[3]="";
stringList1[4]="";
stringList1[5]="";
int sum=0;
//read input
boolean valid=true;
for (int i=1; i<6;i++)
{
System.out.print(+i+". Enter string:" );
stringList1 [i] =stringList.nextLine();
do {
valid = true;
if (stringList1==target1 ){
int[] array = new int[5];
Random rnd = new Random();
array[i]=rnd.nextInt();
}
}while (!valid);
Scanner target = new Scanner (System.in);
//creating target string
String target1 = target.nextLine();
System.out.println("Enter target:");
}
}
public static int hammingdistance(String target1,String stringList1) {
int distance=0;
if( target1.length() != stringList1.length())
{
return -1;
}
else
{
for(int i=0;i<target1.length();i++)
{
if(target1.charAt(i)!=stringList1.charAt(i))
distance++;
}
return distance;
}
}
public static void bubbleSort(int[]ar){
boolean sorted = false;
sorted = true;
for (int i=0;i<ar.length-1;i++)
if (ar[5]>ar[i+1]){
int tmp = ar[i];
ar[5]=ar[i+1];
ar[i+1]=tmp;
sorted = false;
}
}
}
import java.lang.*;
public class Main
{
public static void main(String[] args)
{
String [] strInput1 = {"After ","blackboard ","Contents ","distances","Hamming "};
String [] strInput2 = {"two ","static ","array ","local ","find "};
int [] intResult = new int [strInput2.length] ;
for (int i = 0 ; i< strInput2.length ; i++)
{
intResult[i] = Math.abs(strInput1[i].length() - strInput2[i].length());
System.out.println(intResult[i]);
}
}
}

how do you split a string of numbers into separate integers and use those in a loop? (java)

i have a project wherein i have to create multiple classes that form the image of each (ex: Digit0, Digit1,...,Digit9) with a small and a large size. there are 10 different classes so i'll just simplify to what's important. (for example class Digit1 contains a print function that outputs a small number 1 or a big number 1). i have no problem creating the classes for these digits, where i'm stuck is in figuring out the tester program.
the tester program should allow the user to input a number (ex: 1, 25, 4354435454 etc.) and input a size (1 for small, and 2 for large) and print out the desired images. so far i have this code and it works but it only allows single digit numbers
import java.util.Scanner;
public class DigitDisplay
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int digits = scan.nextInt();
int segmentSize = scan.nextInt();
while ((digits!=0)&&(segmentSize!=0)) //terminates when 0 0 is input
{
if (digits==0)
{
if (segmentSize==1) //this is the small size
{
Digit0 small = new Digit0(1);
//this references the small sized 0 created as a method in class Digit0
System.out.println(small.toString());
//this prints the small digit 0
}
else //this is the large size
{
Digit0 big = new Digit0(2);
System.out.println(big.toString());
}
}
//...the other digits are placed as else ifs
}
}
}
i tried altering the scanner objects so that it takes in String digits instead of int digits. so that i could simply split it and use a for loop to go through each character of the string, but i can't seem to get it to work. i really hope i made sense here. i'm a beginner and would really appreciate the help
import java.util.Scanner;
public class DigitDisplay
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
String digits = scan.next(); //takes in a string of numbers
digits.split(" "); //splits the string into its digits
//int segmentSize = scan.nextInt(); commenting this out because it works. just need to focus on the
digits themselves
while ((!digits.equals("0")) && (segmentSize!=0)) //terminates when input is 0 0
{
for (int i=0; i<digits.length(); i++) //goes through all digits of string
{
int num = digits.charAt(i);
switch (num)
{
case 0:
System.out.println("zero"); //there is a longer code referencing the two sizes but the sizes work but i simplified it again. this is just for me to know whether it is printing the right thing
break;
default:
System.out.println("other"); //these are the other digits, but i just condensed them together just to see if its printing right
break;
}
}
digits = scan.next();
digits.split(" ");
//segmentSize = scan.nextInt();
}
}
}
when i input 002, i want to ouput:
zero
zero
other
but instead, it just outputs "other" for all three.
Looking at the question, I think this is what you're looking for:
Scanner scan = new Scanner (System.in);
String digits = scan.nextLine(); //takes in a string of numbers.
int[] digits_split = new int[0]; //creates an int array to store split digits.
digits_split = digits.split(" "); //splits the string into the digits_split array.
By creating an int array it's now easier to validate the digits.
now you can use this loop to check your split digits:
note below is Pseudo Code and has not been tested...
for(int i = 1; i <= digits.length; i++)
{
if(digits_split[i]=0)
{
System.out.println("zero");
}
else
{
System.out.println("other");
}
}
Also ensure that when entering your digits you put a space in between each one so when the program requests for digits you type: 0 0 2
EDIT:
If your digits contain commas use:
digits = digits.replace(",","");
Also once you've split the string use trim:
digits = digits.trim();
It tidy's things up a little.
ALSO:
when i input 002, i want to ouput:
You need to input: (0[space]0[space]2) to get the output you want. As you're splitting on a " ". Otherwise use a symbol.
Hope this helps,
Rob.

Ascending a String input of numbers in java

I am working on a program where user can input random numbers and when user give -1 the loop will break and the entered numbers will be displayed
Example:
Enter a Number: 32
Enter next Number: 1243
Enter next Number: 123
Enter next Number: 76
Enter next Number: -1
Thank You. You have entered 32, 1243, 123, 76
Now whatever number is entered it will be displayed in ascending order
----Ascending order -----
[32,76,123,1243]
Now i have completed the following but the to get exact result the user need to enter
->0032
->0076
->0123
->1243
Then i am getting the exact result
[0032, 0076, 0123, 1234]
Then only my sorting is working fine otherwise it is like
[ 123, 1243, 32, 72]
Now how to solve this ?
package Testx;
import java.util.Arrays;
import java.util.Scanner;
public class Test7Ctr{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner user = new Scanner(System.in);
String user_input = "";
String holdv="";
String holdvx="";
String ascend="";
//AsveNd(user_input);
try
{
int b =0;
do
{
System.out.print("Enter next number:");
user_input = user.nextLine();
int x= Integer.valueOf(user_input);
if (x != -1)
{
holdv=user_input;
holdvx+=holdv+",";
ascend+=holdv+" ";
b++;
}
else
{
System.out.println("THANK YOU FOR ENTERING= "+holdvx);
break;
}
}
while(b <= 100);
{
}
String[] numbers=ascend.split("\\s");
for(String numb:numbers)
{
int intarray[] = new int[numbers.length];
Arrays.sort(numbers);
//break;
}
System.out.println("---Ascending order---");
System.out.println(Arrays.toString(numbers));
}
catch(Exception e)
{
}
}
}
You are sorting strings rather than numbers. This makes your sort work in lexicographic order instead of plain ascending order.
So to fix your problem, simply add Integers and not Strings. You can even parse a String to an Integer using Integer.parseInt().
Also, there is no need to call sort every time you insert a new number, but just once in the end. That adds a lot of overhead to your process.
You can get the proper integer sorting with the following:
String[] numbers = ascend.split("\\s");
int intarray[] = new int[numbers.length];
int i = 0;
for (String numb : numbers)
{
// convert the String to an int
intarray[i++] = Integer.parseInt(numb);
}
Arrays.sort(intarray); // sort the int array, not the String array
System.out.println("---Ascending order---");
System.out.println(Arrays.toString(intarray));
Side Note:
Your do/while loop would be better written as:
int x = 0;
do
{
System.out.print("Enter next number:");
user_input = user.nextLine();
x = Integer.valueOf(user_input);
if (x != -1)
{
holdv = user_input;
holdvx += holdv + ",";
ascend += holdv + " ";
}
} while (x != -1);
System.out.println("THANK YOU FOR ENTERING= " + holdvx);
You don't need the int b
You don't need the else statement in the loop. Just have the loop terminate when x is -1.
Also, you had an empty block after the while (...); That is not doing anything. The while portion of a do/while loop has no body.
You are sorting the "Strings" and not the "numbers". Scan those inputs as number, put them to a dynamic list (and not a static sized array) and then sort the list of numbers (and not of string)

Why does my program keep looking for inputs?

This code is in Java. It allows me to enter the first input fine, but after the second is inputted it keeps looking for more strings, none of the rest of my code follows. Idealy the code will find if 2 strings are anagrams, but I have not been able to test this due to this annoying problem.
import java.util.*;
public class Anagram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word");
String first = scan.nextLine();
System.out.println("Please enter a second word");
String second = scan.next();
first = first.toLowerCase();
second = second.toLowerCase();
int lengthF = first.length();
int lengthS = first.length();
int x = 0;
int y = 0;
int placeF=0;
int placeS=0;
char g = 97;
int count =0;
if(lengthF != lengthS)
{
System.out.println("The words are not anagrams");
x=1;
}
while(x == y||g<123)
{
x=0;
y=0;
for(int i = 0;i<lengthF;i++)
{
if(first.charAt(i)==g)
{
x++;
}
}
for(int i = 0;i<lengthS;i++)
{
if(second.charAt(i)==g)
{
y++;
}
}
count++;
g++;
}
if(count==23)
System.out.println("Anagram");
else
System.out.println("Not Anagram");
}
}
I've spotted three bugs in your code, which you can easily find by yourself if you always follow these general rules for programming:
Never use numbers obscurely. Write them in a way that explains where that value comes from: Instead of:
char g=97;
... let it be:
char g='a';
And the same goes for every single "special" number in your program: 97, 123 and 23 (In this way you'll see 23 is wrong).
Indexed loops should be always for, with its initial value, its ongoing condition and its increment operation. Ongoing condition must be the index interval condition, plus optional secondary conditions combined by AND operators.
And the third bug... Well, right now I cannot think of any general rule to avoid it. It must have been a copy-and-paste issue: The variable lengthS is wrongly initialized.
Also, I recommend you not to code the same algorithm more than once: Take it out to an individual function and reuse it. So you can do with the loop that counts the number of occurrences of a certain char within a certain string. You could define it like this:
private static int countOccurrencesOfChar(String s, char c) {...}

What's the best method of finding integers in a string?

Hello StackOverflow community! I'm student trying to solve this problem....
The main issue I am having with it is that I dont know the best way to find characters that are valid integers in Strings.
Note: I am only 1 month into learning Java, and I spent most of last year learning python. So compiler languages are new to me.
Write a program that reads in a product code and outputs whether it is valid or not based on some simple rules.
The rules:
1st part can contain only capital letters and 6 digits. 2nd part is alldigits and = the product of the first 6 digits taken in groups of two from the left.
eg: AX6BYU56UX6CV6BNT7NM 287430
is valid because 65*66*67 = 287430
This is what I have so far
import java.util.*; //import java utilities
public class Basic5{ //declares my class
public static void main(String[]args){
Scanner kb=new Scanner(System.in);//creates Scanner for user input
String userentry=kb.nextLine(); //Takes users input as a string
String result="Valid"; //Variable for if the code is Valid
int DoubleCounter=0; //Counter for number of ints
double newdouble;
List<Double> NumberList = new ArrayList<Double>(); //Creates Array List for tracking Doubles
for(int i=0;i<userentry.length();i++){ //checks length of Users input
if(Character.isLowerCase(userentry.codePointAt(i))){ //checks if its a Lowercase letter
result="Fail"; //Changes result variable
if(Integer.parseInt(userentry,i)){ //checks if character from input is a valid integer
DoubleCounter+=1; //Adds to DoubleCounter
newdouble=userentry.charAt(i); //Isolates character
NumberList.add(newdouble); //Adds it to List of doubles
}
}
}
}
}
You can use following methods to check whether the input is a char or digit :
Character.isDigit('A');
Character.isLetter('A');
Here's one way to do it:
#Test
public void testExample() {
assertTrue(isValid("AX6BYU56UX6CV6BNT7NM 287430"));
assertFalse(isValid("AX6BYU56UX6CV6BNT7NM 287431"));
}
private boolean isValid(String s) {
String[] parts = s.split(" ");
int[] ints = extractIntegers(parts[0]);
int target = Integer.parseInt(parts[1]);
return product(ints) == target;
}
private int[] extractIntegers(String s) {
String digits = s.replaceAll("\\D+", "");
int[] ints = new int[digits.length() / 2];
for (int i = 0; i < digits.length(); i += 2) {
ints[i / 2] = Integer.parseInt(digits.substring(i, i + 2));
}
return ints;
}
private int product(int[] ints) {
int result = 1;
for (int num : ints) {
result *= num;
}
return result;
}
It assumes that there are non-zero even number of digits in the first part of the string. If you need to handle other cases, it should be easy to do, based on this.
String str = "AX6BYU56UX6CV6BNT7NM 287430";
str = str.replaceAll("[^0-9]+", "");

Categories