I'm practicing learning Java and I found this exercise online to input a long integer (ex 2827) and then calculate how many different digits there is in the integer (2,8 and 7) = 3 in this case.
I'm considering using a for loop and then with subString, comparing if the number equals each others and they (tutorial) suggest that I should use an array "used" to register which numbers appear, nonetheless
This is what I've got so far:
import java.util.Scanner;
public class UniqueInteger {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean[] used = new boolean[10];
int uniqueNbr = 0;
System.out.print("Input an integer: ");
String nbrString = String.valueOf(scan.nextLong());
for (int i = 0; i < nbrString.length(); i++) {
String bigI = String.valueOf(i);
if(nbrString.substring(i,(i+1)).equals(bigI)){
uniqueNbr++;
}
}
System.out.println("Amount of unique digits: " + uniqueNbr);
}
}
My problem is now that this code does not work, and I'm not sure I'm taking the right approach here. I've also not found a reason or purpose to include the boolean array "used".
What's wrong with my code?
How do I in a smart way use the boolean array and make my code more efficient?
You need to check if the current number in the string has been used (using your boolean array). If it hasn't been used, set used[num] to true and increment uniqueNbr.
import java.util.Scanner;
public class UniqueInteger {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean[] used = new boolean[10];
int uniqueNbr = 0;
System.out.print("Input an integer: ");
String nbrString = String.valueOf(scan.nextLong());
for (int i = 0; i < nbrString.length(); i++) {
int num = Character.getNumericValue(nbrString.charAt(i));
if(!used[num]) {
uniqueNbr++;
used[num] = true;
}
}
System.out.println("Amount of unique digits: " + uniqueNbr);
}
}
Related
As title said, I want to randomly generate a 4-digit number (it's okay to have zero in the first digit), but the number itself couldn't contain the same number.
For example, 1234 is okay, 2234 is not okay, because 2 has repeated.
Moreover, if it got repeated, then create another number again until the 4-digit number has no longer the same number within.
I couldn't figure it out. I stuck on some point, especially in while-loop.
Here's my code with C#.
Please help me with this.
public class GuessNumber
{
public int[] answer;
public void newGame()
{
int[] answer = new int[4];
var random = new Random(Guid.NewGuid().GetHashCode());
for (int i = 0; i < answer.Length; i++)
{
answer[i] = random.Next(0, 10);
}
this.answer = RandomCheck(answer);
}
public int[] RandomCheck(int[] answer)
{
bool repetition = true;
for (int i = 0; i < answer.Length; i++)
{
do
{
repetition = false;
for (int k = 0; k < i; k++)
{
if (answer[i] != answer[k]) continue;
else
{
newGame();
continue;
}
} while (repetition);
return answer;
}
Please help with this, make it could automatically generate the right number.
I'm supposed to use two methods to hold arrays, then with the two arrays determine win % of the rockets, average margin of score difference for the games lost by Houston Rockets, and the lowest Houston Rockets’ score and the corresponding game number. I primarily need help with the first one, and I can get the other tasks. I just dont know how to pass arrays from methods very well. Any help would be useful, THanks!
import java.util.Scanner;
public class MorenoJonathonRocketsStatistics
{
public static void main(String[] args)
{
System.out.println("enter rockets game scores");
int[] rockets = rocketsScore();
System.out.println("enter opponents scores");
int[] opponents = opponentsScore();
int per = percent();
System.out.println("game win percent"+per+" %");
}
public static int[] rocketsScore()
{
Scanner sc = new Scanner(System.in);
int[] rocketsScore = new int[8];
for(int i=0;i<rocketsScore.length;i++)
{
rocketsScore[i] = sc.nextInt();
}
return rocketsScore;
}
public static int[] opponentsScore()
{
Scanner sc = new Scanner(System.in);
int[] opponentsScore = new int[8];
for(int i=0;i<opponentsScore.length;i++)
{
opponentsScore[i] = sc.nextInt();
}
return opponentsScore;
}
public static int percent(int[] array, int[] array2)
{
int[] rock = rocketsScore.length();
int[] opp = opponentsScore.length();
double percent=0;
int w=0, l=0;
for(int i=0; i<rocketsScore.length;i++)
{
if(rocketsScore[i]>opponentsScore[i])
{
w++;
}
else{
l++;
}
}
percent = w/l;
return percent;
}
}
To pass array in methods, you don't need to put any brackets beside the variable that is holding the array. So, you may want to do it like below:
int per = percent(rockets, opponents);
I have to find the LCM of two integers using the prime factors method and function calls.
I'm up to making a function to find the prime factorization of the first number, but I'm getting errors at int x = first_number; and with System.out.print(primeFactorization).
This is my code so far:
import java.util.Scanner;
public class lcm {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int first_number;
int second_number;
System.out.print("Enter an integer: ");
first_number = reader.nextInt();
System.out.print("Enter another integer: ");
second_number = reader.nextInt();
}
public static int primeFactorization(int[] pfArray) {
int counter = 0;
pfArray = new int[10]; //created array in memory
int x = first_number;
for(int i=2;i<=x;i++){
while(x%i==0){
x=x/i;
pfArray[counter] = i;
++counter;
}
}
for(int i=0;i<counter;i++){
System.out.println(pfArray[i]);
}
}
System.out.println(primeFactorization);
}
I am just starting to learn Java, so please answer in very basic terms!
Thanks so much!
The variable first_number is declared in the first method and so cannot be used within the second method unless you pass it in as a parameter.
The only thing called primeFactorisation is the method. System.out.println requires an object (a variable) as its input. So you can't do it like that.
I am a complete newbie to Java programming, I want to dynamically create objects in Java during run time, I have checked the forms and tried some code but nothing really seems to work.
here is my code .. all help is really appreciated :)
import java.util.Scanner;
public class Main{
public static void main(String[] args){
String carName;
String carType;
String engineType;
int limit;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of Cars you want to add - ");
limit = in.nextInt();
for(int i = 0; i <limit; i++){
Cars cars[i] = new Cars();
System.out.print("Enter the number of Car Name - ");
carName = in.nextLine();
System.out.print("Enter the number of Car Type - ");
carType = in.nextLine();
System.out.print("Enter the Engine Type - ");
engineType = in.nextLine();
cars[i].setCarName(carName);
cars[i].setCarType(carType);
cars[i].setEngineeSize(engineType);
String a = cars[i].getCarName();
String b = cars[i].getCarType();
String c = cars[i].getEngineeSize();
System.out.println(a,b,c);
}
}
}
The cars class looks like this ..
public class Cars{
public String carName;
public String carType;
public String engineeSize;
public void Cars(){
System.out.println("The Cars constructor was created ! :-) ");
}
public void setCarName(String cn){
this.carName = cn;
}
public void setCarType(String ct){
this.carType = ct;
}
public void setEngineeSize(String es){
this.engineeSize = es;
}
public String getCarName(){
return this.carName;
}
public String getCarType(){
return this.carType;
}
public String getEngineeSize(){
return this.engineeSize;
}
}
You're on the right track, there are a few errors and unnecessary bits though.
The Cars Class
Your Cars class was mostly fine, (though in my opinion Car would have made more sense) however your constructor didn't make sense, you had public void Cars(), void means "this method returns nothing", but you want to return a Cars object, meaning your constructor needs to become:
public Cars()
{
System.out.println("The Cars constructor was created ! :-) ");
}
Your Main Class
You were very close here as well, your primary issue was creating the cars array limit times:
for(int i = 0; i < limit; i++)
{
Cars cars[i] = new Cars();
//Other code
}
The array needs to be made outside the for loop.
Here is the revised Main class in full, the comments should explain fairly well what I did and why.
import java.util.Scanner;
public class Main{
public static void main(String[] args){
//The strings here were unnecessary
int limit;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of Cars you want to add - ");
limit = in.nextInt();
in.nextLine(); //nextInt leaves a newLine, this will clear it, it's a little strange, but it makes sense seeing as integers can't have newlines at the end
//Make an array of Cars, the length of this array is limit
Cars[] cars = new Cars[limit];
//Iterate over array cars
for(int i = 0; i < limit; i++)
{
//Read all the properties into strings
System.out.println("Enter the number of Car Name - ");
String carName = in.nextLine();
System.out.println("Enter the number of Car Type - ");
String carType = in.nextLine();
System.out.println("Enter the Engine Type - ");
String engineType = in.nextLine();
//Set the object at current position to be a new Cars
cars[i] = new Cars();
//Adjust the properties of the Cars at this position
cars[i].setCarName(carName);
cars[i].setCarType(carType);
cars[i].setEngineeSize(engineType);
//We still have the variables from the scanner, so we don;t need to read them from the Cars object
System.out.println(carName+carType+engineType);
}
in.close(); //We don't need the scanner anymore
}
}
Finished typing this and realized that the question is two years old :)
Before I state my question, I would like to thank everyone who helped me on my previous question. Anywho, I am currently getting the memory offsets as result even when I place it to the to a toString method. I've read most of the questions regarding the toString method and have somewhat of a understanding, I just wanted to make sure if I'm implementing this correctly. If you feel that this is a redundant question, I understand. Thanks for the help in advance.
Ship class
import java.util.Scanner;
public class Ship{
int type;
public String [][] shipPiece = new String[11][11];
Scanner in = new Scanner(System.in);
//Coordinate xy = new Coordinate();
//private Coordinate[] bawdPiece = {new section()};
public Ship(){
}
public String[][] placeShip()
{
System.out.println();
for(int x = 1; x<10; x++)
{
for(int y = 1; y<10; y++)
{
shipPiece[x][y] = "0";
System.out.print("|" + shipPiece);
}
}
return shipPiece;
}
public String toString()
{
StringBuilder temp = new StringBuilder();
temp.append(shipPiece);
return temp.toString();
}
public String toString()
{
StringBuilder temp = new StringBuilder();
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
temp.append(String.valueOf(shipPiece[x][y]);
}
temp.append("\n");
}
return temp.toString();
}
Also another thing I would like to point out is your array initialization. You initialize it with 11 x 11 indices, but your loop is only adding 9 values to each row and column Loop starts at 1 and ends at 9. You may want to fix your initialization to 10 x 10 and make your loop start at 0.
If I understand the question correctly, you are trying to get the index of the shipPiece as a string?
If that's the case try String.ValueOf(index), you'll obviously have to do this twice as you have a 2-dimensional array.
Ex:
String s = String.ValueOf(xIndex) + "," + String.ValueOf(yIndex);