I am begginer.While compiling this code
class UpperLowerCase
{
static String ini = "I LOVE JAVA";
static char str[] = ini.toCharArray();
static char invr[] = new char[10];
static int len = 0 , len1 = 0, i;
static void toUpper()
{
for(i=0;i<str.length;i++)
{
if(str[i]>=97 && str[i]<=122)
invr[len1++]=(str[i]-32);
else
invr[len++]=str[i];
}
invr[len1]='\0';
System.out.println("Reverse of"+ str+" is \n"+ invr);
}
static void toLower()
{
for(i=0;i<str.length;i++)
{
if(str[i]>=65 && str[i]<=90)
invr[len1++]=str[i]-32;
else
invr[len++]=str[i];
}
invr[len1]='\0';
System.out.println("Reverse of"+ str+" is \n"+ invr);
}
public static void main(String [] args)
{
toUpper();
}
}
I get error "possible lossy conversion from int to char"
How to convert int to char.
Please help me by telling how to resolve this error?
You can have an overflow when doing mathematic opetations between integers and chars, this can affect the expected result since that value is going to be assigned to a char... here you have
invr[len1++] = str[i]-32;
but you should cast to char like:
invr[len1++] = (char)(str[i]-32);
Related
I was asked to write a class NumberOcc with these methods:
-method getNbOcc which takes as arguments a string str and a character 'c' and return the number of occurence of the character 'c'.
-method dspNbOcc which displays the value returned by getNbOcc
-method getNbVoy which returns the number of vowel inside a string str
-method dspNbVoy which displays the value returned by getNbVoy
The problem is the value returned by getNbVoy is wrong, example: for str=stackexchange it returns 34 vowels.
public class NumberOcc {
static int count1=0;
static int count2=0;
public static int getNbOcc(String str, char c) {
for(int i=0;i<str.length();i++) {
if (str.charAt(i)==c)
count1++;}
return count1;
}
public static void dspNbOcc() {
System.out.println(count1);
}
public static int getNbVoy(String str) {
String vowel="aeiouy";
for(int j=0;j<vowel.length();j++) {
count2+=getNbOcc(str,vowel.charAt(j));}
return count2;
}
public static void dspNbVoy() {
System.out.println(count2);
}
}
TestClass
public class TestNumberOcc {
public static void main(String[] args) {
String str="stackexchange";
NumberOcc.getNbOcc(str, 'e');
NumberOcc.dspNbOcc();
NumberOcc.getNbVoy(str);
NumberOcc.dspNbVoy();
}
}
Thanks for helping
Remove the static fields, pass the values to the methods. And use them to display the results. Like,
public static int getNbOcc(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
public static void dspNbOcc(String str, char c) {
System.out.println(getNbOcc(str, c));
}
public static int getNbVoy(String str) {
int count = 0;
char[] vowels = "aeiouy".toCharArray();
for (char ch : vowels) {
count += getNbOcc(str.toLowerCase(), ch);
}
return count;
}
public static void dspNbVoy(String str) {
System.out.println(getNbVoy(str));
}
And then testing everything is as simple as
public static void main(String[] args) {
String str = "stackexchange";
NumberOcc.dspNbOcc(str, 'e');
NumberOcc.dspNbVoy(str);
}
the issue is you're not initializing your count1 (nor count2, but that bug doesn't affect anything in this case) at the beginning of your count method... add this line to the beginning of your getNbOcc method before the loop:
public static int getNbOcc(String str, char c) {
count1 = 0; // add this line
for(int i=0;i<str.length();i++) {
The solution is to apply what you did in your countLetterInString function to countVowelsInString. Just remember to use local variables. You will run into issues with static/global variables if the function is called more than once, but local variables will work the same way every time.
public static int countVowelsInString(String str) {
String vowels = "aeiouy";
// Move counter into the function
int numVowels = 0;
for(int j = 0;j<vowel.length();j++) {
numVowels += getNbOcc(str, vowel.charAt(j));
}
return numVowels;
}
package dspermutation;
import java.util.Scanner;
public class DSPermutation {
String s;
char[] c;
int n;
public static void main(String[] args) {
DSPermutation ds=new DSPermutation();
ds.input();
}
private void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
s=sc.next();
c=s.toCharArray();
n=c.length;
permutation(c,n-1,0);
}
private void permutation(char[] cc,int nn,int ii) {
if(ii==nn)
{
System.out.println(cc);
}
else
{
for(int j=ii;j<=nn;j++)
{
swap(cc[ii],cc[j]);
permutation(cc,nn,ii+1);
swap(cc[ii],cc[j]);
}
}
}
private void swap(char p, char c0) {
int x=s.indexOf(p);
int y=s.indexOf(c0);
/*1*/ char temp=c[x];
/*2*/c[x]=c[y];
/*3*/c[y]=temp;
/*c[x]=c0;
c[y]=p;*/
}
}
The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?
Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.
You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.
private void swap(char p, char c0) {
int x = s.indexOf(p);
int y = s.indexOf(c0);
// char temp = c[x];
// c[x] = c[y];
// c[y] = temp;
c[y] = p;
c[x] = c0;
s = String.valueOf(c);
}
I am trying to convert int to binary and i am doing below code.
public static String intToBinary16Bit(String strInt) {
String bin = Integer.toBinaryString(strInt);
return String.format("%016d", Integer.parseInt(bin));
}
So, if i am giving strInt = 0211 than it is working fine and giving the output
0000001000010001.
But, if i am giving strInt = 4527 than it is throwing NumberFormateException.
How can I resolved this issue ?
Try what eznme suggests here:
public class A {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(a);
int bit=1;
for(int i=0; i<32; i++) {
System.out.print(" "+(((a&bit)==0)?0:1));
bit*=2;
}
}
}
Try the following method, it uses recursion for conversion.
private static void toBinary(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return;
}
remainder = number % 2;
toBinary(number >> 1);
System.out.println(remainder);
}
You try:
Long.toBinaryString(2199023255552L);
Java long to binary
I made an object, MyString. I can't figure out how to recreate valueOf(double d). I recreated valueOf for integers. Just to make it easier I limited the amount of decimal places to 8. How can I recreate valueOf(double d)?
public class MyString {
private char[] a;
public MyString(String s) {
this.a = s.toCharArray();
}
public MyString(char[] a) {
this.a = a;
}
public String toString() {
return new String(a);
}
public int length() {
return a.length;
}
public char charAt(int i) {
return a[i];
}
public static MyString valueOf(int i) {
int digits = (int)(Math.log10(i)+1);
char[] b = new char[digits];
for (int j = 0; j < digits; j++) {
b[j] = (char) (48 + i / 10);
i = i % 10;
if (i < 10) {
b[j + 1] = (char)(48 + i);
break;
}
}
MyString ms = new MyString(b);
return ms;
}
public static MyString valueOf(double d) {
char[] d1 = new char[digits];
//Take each digit of the number and enter it into the array
MyString ms = new MyString(d1);
return ms;
}
public static void main(String[] args) {
}
}
I assume you are doing this for fun... so here is the approach I took. You have valueOf(int i) already, so why not basically reuse that function. Just take the double and keep multiplying it by 10 until you have an int. Keep track of where the decimal place goes, then you basically call your valueOf(int i) but also include the decimal point.
I had trouble running your code so I re-did valueOf(int i) then created valueOf(int i, int decimalSpot), passing in -1 or 0 for the decimal spot then it's an integer value and don't use a decimal place.
Anyway, here is what I came up with. It's late, so probably not the cleanest code, but should give you a proof of concept.
public class MyString {
private char[] a;
public MyString(String s) {
this.a = s.toCharArray();
}
public MyString(char[] a) {
this.a = a;
}
public String toString() {
return new String(a);
}
public int length() {
return a.length;
}
public char charAt(int i) {
return a[i];
}
public static MyString valueOf(int i) {
return MyString.valueOf(i,-1);
}
public static MyString valueOf(double d) {
int decimalPlace = 0;
while (d != (int)d)
{
decimalPlace++;
d = d*10;
}
return MyString.valueOf((int)d,decimalPlace);
}
public static MyString valueOf(int i, int decimalSpot) {
int index=0;
int digits = (int)(Math.log10(i)+1);
int stringLength=digits;
if (decimalSpot == 0) decimalSpot=-1; // Don't return 1234. - just return 1234
if (decimalSpot != -1)
{
// Include an extra spot for the decimal
stringLength++;
}
char[] b = new char[stringLength];
for (int j = digits-1; j >= 0; j--) {
int power = (int) Math.pow(10,j);
int singleDigit = (int) Math.floor(i/power);
i = i - power*singleDigit;
b[index++] = (char) (48 + singleDigit);
if (decimalSpot==j)
{
b[index++] = '.';
}
}
MyString ms = new MyString(b);
return ms;
}
public static void main(String[] args) {
MyString ms = MyString.valueOf(12345);
System.out.println(ms);
ms = MyString.valueOf(12345.12313);
System.out.println(ms);
}
}
Rather than trying to solve this problem for every possible source datatype you should be just concentrating on constructing your class from a String. Then all you have to do is delegate this method and all the others you haven't done yet to the corresponding String method in each case, take the resulting String, and construct your object with that String.
I want the user to input a DNA sequence, if it doesn't have the letters A, C, T, or G then it should print out an error. But how can I scan the string entered for those specific characters in the constructot method DNASequence?
heres what I have so far.
import java.util.*;
public class DNASequence {
private String DNASequence;//create a private static variable that can be accessed
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please input a sequence of DNA: ");
String DNAInput = input.nextLine();
}
public DNASequence(String DNAStrand){//Constructor Method that takes parameter a string and checks to see if its only A, T, C, G.
DNASequence = DNAStrand;
// Invoke the countLetters method to count each letter
int[] counts = countLetters(DNAStrand.toUpperCase());
// Display results
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0)
System.out.println((char)('a' + i) + " appears " +
counts[i] + ((counts[i] == 1) ? " time" : " times"));
}
}
/** Count each letter in the string */
public static int[] countLetters(String s) {
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)))
counts[s.charAt(i) - 'a']++;
}
return counts;
}
public String toString(){//Method that just returns the stored sequence
return DNASequence;
}
private static char NucleotideBaseCount(char BaseCount){//Method to count bases
}
private static boolean isSubsequenceOf(String DNAStrand){
}
}
You could use the following regular expression for this: ^[ACTG]+$.
To match the input string against the regex, use String.matches().
Here in a sample implementation based on #NPE 's comment:
import java.util.*;
public class DNASequence
{
private String DNASequence = null; //create a private static variable that can be accessed
public static void main(String[] args)
{
System.out.println("Please input a sequence of DNA: ");
DNASequence dnaS = new DNASequence((new Scanner(System.in)).nextLine().toUpperCase());
}
//Constructor Method that takes parameter a string and checks to see if its only A, T, C, G.
public DNASequence(String DNAStrand) throws IllegalArgumentException
{
if (DNAStrand.matches("^[ATCG]+$"))
{
DNASequence = DNAStrand;
}
else
{
throw new IllegalArgumentException("DNA Sequences should only contain A, T, C, G charaters");
}
}
/** Count each letter in the string */
public int[] countLetters() throws IllegalArgumentException
{
int[] counts = new int[4];
if (DNASequence != null)
{
for (int i = 0; i < DNASequence.length(); i++)
{
switch (DNASequence.charAt(i))
{
case 'A':
counts[0]++;
break;
case 'T':
counts[1]++;
break;
case 'C':
counts[2]++;
break;
case 'G':
counts[3]++;
break;
default:
throw new IllegalArgumentException("DNA Sequences should only contain A, T, C, G charaters, found: " + DNASequence.charAt(i));
}
}
}
return counts;
}
//Method that just returns the stored sequence
public String toString()
{
return DNASequence;
}
private char NucleotideBaseCount(char BaseCount){//Method to count bases
return 'a'; // replace with real implementation
}
private boolean isSubsequenceOf(String DNAStrand)
{
return false; // repalce with real implementation
}
}