I am trying to understand the following code below [duplicate] - java

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 3 years ago.
I am getting a different value when I am performing the iteration manually on
"welcometojava"
when the value of i=5
I am getting following value of variable
when i=5;
substring =MET
smallest="com"
largest="ome"
At this point, the value that I am getting is not validating both the if conditions
I want help with the values of all 3 variables on each iteration so that I can know where I am getting
wrong.Thankyou
public class Solution {
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
smallest = largest = s.substring(0, k);
for (int i=1; i<s.length()-k+1; i++) {
String substr = s.substring(i, i+k);
if (smallest.compareTo(substr) > 0)
smallest = substr;
if (largest.compareTo(substr) < 0)
largest = substr;
}
return smallest + "\n" + largest;
}

If you are not using a debugger, you can trace the values by printing them e.g. I've added System.out.println("i=" + i + ", substring=" + substr + ", smallest=" + smallest + ", largest=" + largest); into your code as follows and also shown the output below it to help you understand how your code is behaving:
public class Solution {
public static void main(String[] args) {
getSmallestAndLargest("welcometojava", 3);
}
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
smallest = largest = s.substring(0, k);
for (int i = 1; i < s.length() - k + 1; i++) {
String substr = s.substring(i, i + k);
if (smallest.compareTo(substr) > 0)
smallest = substr;
if (largest.compareTo(substr) < 0)
largest = substr;
System.out.println("i=" + i + ", substring=" + substr + ", smallest=" + smallest + ", largest=" + largest);
}
return smallest + "\n" + largest;
}
}
Output:
i=1, substring=elc, smallest=elc, largest=wel
i=2, substring=lco, smallest=elc, largest=wel
i=3, substring=com, smallest=com, largest=wel
i=4, substring=ome, smallest=com, largest=wel
i=5, substring=met, smallest=com, largest=wel
i=6, substring=eto, smallest=com, largest=wel
i=7, substring=toj, smallest=com, largest=wel
i=8, substring=oja, smallest=com, largest=wel
i=9, substring=jav, smallest=com, largest=wel
i=10, substring=ava, smallest=ava, largest=wel
In a similar way, you can add some more print statements e.g. to print the value of smallest.compareTo(substr) > 0 and so on to trace your code to a deeper level. However, I strongly recommend you use a debugger to do so.

Related

Adding numbers 1 to n with a loop

So the code posted works and seems to give correct values. The only problem is that it prints every line in the loop instead of just the answer. How can I make it just print the answer instead of every line leading up to it?
import java.util.Scanner;
public class CountLoop{
public static void main (String[] args){
Scanner in = new Scanner (System.in);
int i = -1;
int limit = 0;
System.out.println("Please enter a number");
String end1 = in.nextLine();
int end = Integer.parseInt(end1);
while (i < end){
i++;
limit = (i + limit);
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
}
}
}
I'm fine with using other types of loops as well, as I'll need to show an example with all the different types of loops being used anyway, so any help is appreciated.
Move your system.out.println outside of your while loop
while (i < end){
i++;
limit = (i + limit);
}
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
Or the modern version in Java 8:
int sum = IntStream.range(startInclusive,endExclusive).sum();
System.out.println("The sum of the numbers in between " + startInclusive +
" and " + (endExclusive -1) + " is sum = " + sum);
Renamed variables ;-)
limit -> sum
0 -> startInclusive
end -> endExclusive - 1

Counting Digits in a String - output not being correctly printed

My problem is to count digits in a given string,
here's the code:
public static void main(String[] args) {
String s=" 1 3 4 5 22 3 2";
int[] counts=count(s);
for(int i=0;i<s.length();i++) {
if(counts[i]==1) {
System.out.println(s.charAt(i) + " appears " + counts[i] +" time");
}
else if(counts[i]!=1 && counts[i]!=0) {
System.out.println(s.charAt(i) + " appears " + counts[i] +" times");
}
}
}
public static int[] count(String s) {
int count[] = new int[99];
for(int i=0;i<s.length();i++) {
if(Character.isDigit(s.charAt(i))){
***count[i]++;***
}
}
return count;
}
the desired output is that if x appears more than once then it should say x appears n times, but my output is something like this Undesired Output
The part I've bolded out is where I localised the problem, I cannot find a way to access that if 2 appears more than once, then count[2] must also gain a +1 value, I've tried using a conversion from String to Int but nothing seemed to work. Thanks in advance!
Well, why didn't you make array of size 10 and keep data in it. Something like that:
public static void main(String[] args) {
String s=" 1 3 4 5 22 3 2";
int[] counts=count(s);
for(int i=0;i<10;i++)
if(counts[i]==1) {
System.out.println(i + " appears " + counts[i] +" time");
}
else if(counts[i]!=1 && counts[i]!=0) {
System.out.println(i + " appears " + counts[i] +" times");
}
}
public static int[] count(String s) {
int count[] = new int[10];
for(int i=0;i<s.length();i++)
if(Character.isDigit(s.charAt(i)))
count[(int)s.charAt(i) - (int)'0']++;
return count;
}
You have the correct check to see if the character is a digit, what you aren't doing correctly is incrementing the correct index. You want to convert the character to a number and use that number as your index. Try this
public static int[] count(String s) {
int count[] = new int[10];
for(int i=0;i<s.length();i++) {
if(Character.isDigit(s.charAt(i)))
{
count[Character.getNumericValue(i)]++;
}
}
return count;
}

How would I determine the smallest value which has been entered?

My code asks the user to enter values of animal species and then displays it back to them. I just need to finally add a part which also tells the user the most endangered animal (the one will the lowest entered number). I've looked around on some places and triec using x< min or x=MAX_VALE etc. I just can't seem to make anything work. Is there a method which would be more appropriate for my program?
import java.util.Scanner;
public class endangered
{
public static void main(String[] param)
{
animal();
System.exit(0);
}
public static void animal()
{
int[] array = new int[5];
int j = 0;
String[] names = {"Komodo Dragon" , "Manatee" , "Kakapo" , "Florida Panther" , "White Rhino"};
System.out.println("Please enter the number of wild Komodo Dragons, Manatee, Kakapo, Florida Panthers and White Rhinos.");
Scanner scan = new Scanner(System.in);
for (int i=0; i<=4; i++)
{
while(scan.hasNextInt())
{
array[j] = scan.nextInt();
int max = array[j];
j++;
if(j==5)
{
System.out.println(array[0] + ", " + names[0]);
System.out.println(array[1] + ", " + names[1]);
System.out.println(array[2] + ", " + names[2]);
System.out.println(array[3] + ", " + names[3]);
System.out.println(array[4] + ", " + names[4]);
}
}
}
}
}
What you can do is sort the array using a built-in method and then retrieve the last value (the greatest) and first value (the smallest).
Arrays.sort(array);
int max = array[array.length - 1];
int min = array[0];
For more on the sort method in Java's Arrays class, here's a description of what it exactly does,
public static void sort(int[] a)
Sorts the specified array into ascending numerical order.
Parameters:
a - the array to be sorted
If you want to get the corresponding animal then I would suggest ignoring the above and use streams in Java 8. Combine the String and int array into one 2D String array. Make the rows equal to the number of animals and the columns equal to 2 (ex: for 5 animals, String[][] array = new String[5][2]). For each row in the 2D array, the first element should be the animal, and the second element should be the size (ex: String [][] array = {{"fox", "1"},{"deer","0"},{"bear", "2"}}). The following will return you a 2D array that is sorted in ascending order and gives you the corresponding animal with it,
String[][] sorted = Arrays.stream(array)
.sorted(Comparator.comparing(x -> Integer.parseInt(x[1])))
.toArray(String[][]::new);
String smallestAnimal = sorted[0][0]; //name of smallest animal
String smallest = sorted[0][1]; //population of smallest animal
String biggestAnimal = sorted[sorted.length - 1][0]; //name of biggest animal
String biggest = sorted[sorted.length - 1][1]; //population of biggest animal
In java 8, you can do something like this:
int min = Arrays.stream(array).reduce(Integer.MAX_VALUE, Math::min);
Update: The user asked for print of the animal as well.
If you need to return the animal as well, it would be best if we edit your code.
We will add 2 more variables. The first one, minVal will contain the lowest number that the user entered. The second one, minValIndex will contain the index of the species with the lowest count.
I removed your while cycle because there was no need for one.
public static void animal()
{
int[] array = new int[5];
int j = 0;
String[] names = {"Komodo Dragon" , "Manatee" , "Kakapo" , "Florida Panther" , "White Rhino"};
System.out.println("Please enter the number of wild Komodo Dragons, Manatee, Kakapo, Florida Panthers and White Rhinos.");
Scanner scan = new Scanner(System.in);
int minVal = Integer.MAX_VALUE;
int minValIndex = -1;
for (int i=0; i<=4; i++)
{
array[j] = scan.nextInt();
if(array[j] < minVal) {
minVal = array[j];
minValIndex = j;
}
int max = array[j];
j++;
if(j==5)
{
System.out.println(array[0] + ", " + names[0]);
System.out.println(array[1] + ", " + names[1]);
System.out.println(array[2] + ", " + names[2]);
System.out.println(array[3] + ", " + names[3]);
System.out.println(array[4] + ", " + names[4]);
}
}
System.out.println("The smallest entered number:" + minVal);
System.out.println("The species:" + names[minValIndex]);
}
You are not calculating max anywhere.
Replace:
int max = array[j]
With:
max = max > array[j] ? max : array[j];
To store the maximum value in the array. (This is a ternary operator)
Now the array have have equal values so in that case take care of this possibility by this code :
for(int i = 0; i <= 4; i++) {
if(array[i] == max) {
System.out.println("Max endangered:" + array[i] + name[i]);
}
}

Concat String in a for loop

I'm trying to create a program that takes each number typed in by the user and sort them out as even, odd and the number zero values.
The result should look like something like this:
User Input: 14005
Output:
Even Numbers: 4
Odd Numbers: 1, 5
Zero's: 0, 0
This is the code I've written, I thought of using string concatination in order to add a new value each time the loop checks for the next character, don't know whether I'm thinking right or not though, would appriciate if someone could tell me where I'm thinking in the wrong way.
package com.craydesign;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
String number = JOptionPane.showInputDialog("Please enter a number: ");
String evenNumbers = "";
String oddNumbers = "";
String numberZero = "";
for(int i = 0; i < number.length(); i++) {
if(number.charAt(i) % 2 == 0) {
evenNumbers.concat(Integer.toString(i) + ", ");
} else if(number.charAt(i) % 2 != 0) {
oddNumbers.concat(Integer.toString(i) + ", ");
} else if (number.charAt(i) == 0){
numberZero.concat(Integer.toString(i) + ", ");
}
}
JOptionPane.showMessageDialog(null, "Even numbers: " + evenNumbers + "\n" + "Odd numbers: " + oddNumbers + "\n" + "Zero's: " + numberZero);
}
}
use Character.getNumericValue() instead of charAt(i)
public static void main(String[] args) throws IOException
{
String number = JOptionPane.showInputDialog("Please enter a number: ");
StringBuffer evenNumbers = new StringBuffer();
StringBuffer oddNumbers =new StringBuffer();
StringBuffer numberZero =new StringBuffer();
for(int i = 0; i < number.length(); i++) {
int value=Character.getNumericValue(number.charAt(i));
if(value!=0 && value % 2 == 0) {
evenNumbers.append(value).append(',');
} else if(value % 2 != 0) {
oddNumbers.append(value).append(',');
} else if (value == 0){
numberZero.append(value).append(',');
}
}
JOptionPane.showMessageDialog(null, "Even numbers: " + evenNumbers + "\n" + "Odd numbers: " + oddNumbers + "\n" + "Zero's: " + numberZero);
}
EDIT:(displaying numbers in sorted order)
String evenNo[]=evenNumbers.toString().split(",");
String oddNo[]=oddNumbers.toString().split(",");
Arrays.sort(evenNo);
Arrays.sort(oddNo);
JOptionPane.showMessageDialog(null, "Even numbers: " + Arrays.toString(evenNo) + "\n" + "Odd numbers: " + Arrays.toString(oddNo) + "\n" + "Zero's: " + Arrays.toString(numberZero.toString().substring(0,
numberZero.length()-1).split(",")));
You are using String for output and appending the output in the string.
Its a bad idea. as String class is immutable so if you do change anything in String it will create a new Object in memory.
So your solution will take extra memory.
Accroding to me you can solve this problem in two ways
Use StringBuffer class instead of String class for appending
Use ArrayList to Store your result. and iterate over the arraylist and show the output as you want.
Thanks,
Aman

Iterate each digit in an integer and do mod 11 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to do some program and need of some help. For example, I entered this number on a textbox: 00669253, then for each number i want to multiply it with the number 87654321 so for example
(0x8) + (0x7) + (6x6).... and so on and then get the sum of all the number and do a mod of 11. How can I do this?
Thanks for your advance help.
You can first convert the number into String and then you can do it like this :
String no1="00669253";
String no2="87654321";
int sum=0;
for(int i=0;i<no1.length();i++){
sum+=Integer.parseInt(""+no1.charAt(i))*Integer.parseInt(""+no2.charAt(i));
}
After that you can do any operation on sum
You can try something like that:
public class TestMult {
public static void main(String[] args) {
String first = "00669253";
String second = "87654321";
long sum = 0L;
if (first.length() == second.length()) {
for (int i = 0; i < first.length(); i++) {
int firstInt = Character.getNumericValue(first.charAt(i));
int secondInt = Character.getNumericValue(second.charAt(i));
sum += firstInt * secondInt;
}
System.out.println("result: " + sum % 11);
} else {
System.err.println("lengths are not equal.");
}
}
}
try this,
public class Dummy {
public static void main(String[] args) {
String s = "112211";
String s2 = "010101";
char[] sDummy = s.toCharArray();
char[] s2Dummy = s2.toCharArray();
int sum = 0;
for (int i = 0; i < sDummy.length; i++) {
System.out.println("multiplying..." + sDummy[i] + "with " + s2Dummy[i] + "and adding prev sum " + sum + " to it");
sum = sum + (Integer.parseInt(sDummy[i] + "") * Integer.parseInt(s2Dummy[i] + ""));
}
sum = sum % 11;
System.out.println("sum with mod is = " + sum);
}
}
You need to add some checks in case if length of both string differs
Try this,
String inputValue = "00669253";
String multipleValue="87654321";
int result = 0;
for (int i = 0; i < inputValue.length(); i++)
{
result += Integer.parseInt(Character.toString(inputValue.charAt(i))) *
Integer.parseInt(Character.toString(multipleValue.charAt(i)));
}

Categories

Resources