i want to know if i can get the last digit of the input, but if the last one is 0 i want it to ignore it and take the one before it... like bob120, last digit is 20 not 0, to make it the level for the person
here is my code and i tried for 2 days to know how but i'm stuck with this problem.
and i tried %10 but still it's the same problem.
number = number.substring(5,6);
level = Integer.parseInt(number);
I'm using scanner package
thank you in advance
if the input is a String and you like the use substring the code will be
int pos= number.lenght();
String lastChar = number.substring(pos-1,pos);
Note: number is a String : )...
Then you are right on the Integer.parseInt(), be aware of error if its not a number (try, catch)...
Then you need a if statement...change your pos and try again....
To do this task it would be better to use the String.toCharArray() at loop it backwards... so if you have time study this..
Something like this:
public int getLastNumDifThenZero(String text){
char[] ca = text.toCharArray();
for (int i = ca.length-1; i >= 0; i--) {
char a = ca[i];
try {
int n = Integer.parseInt(String.valueOf(a));
if (n!=0){
return n;
}
} catch (NumberFormatException e) {
//Not a number
}
}
return -1;
}
You can loop from the end of String and search for 'non-zero' value (result char is String) :
public static void main(String[] args) {
// example returns 7
String num = "85677000";
char lastDigit =' ';
// looping from end and searching non zero digit
for(int i=num.length()-1 ; i>=0 ;i--){
lastDigit=num.charAt(i);
if (lastDigit != '0'){
System.out.println(lastDigit);
break;
}
}
}
Related
my question is if i have a string- with two types of chars in the string '#' and '.' and I want to count how many times I land on '#' if each time I move to the right 3 and down one.
for example the given string would look like the following:
...#.#.......##....#.......#...
.#....#.##.#..#.......#.....##.
#..#...##.####..###.....#......
..#...##...#...#.#......#...#.#
.##.##.#...#.....#.##..##......
.#...#.#.##.###..#...#...#.....
.#..##..#....##.##....##....##.
..#...##....#..###........##...
.#..#..#.#....#.#...#.#......#.
.##.....#...#..#..#..#...###...
.#...#....#..#...........###...
.....#...........##.#......#...
.....#....##......##..#.#......
-1//stops the checking
what should happen is the following, 0 means landed on a . and X means it landed on # which is when count should go up by one each time this happens:
...#.#.......##....#.......#...
.#.o..#.##.#..#.......#.....##.
#..#..0##.####..###.....#......
..#...##.0.#...#.#......#...#.#
.##.##.#...#0....#.##..##......
.#...#.#.##.###0.#...#...#.....
.#..##..#....##.##0...##....##.
..#...##....#..###...o....##...
.#..#..#.#....#.#...#.#.0....#.
.##.....#...#..#..#..#...##X...
.#...#....#..#...........###..0//notice here next round it will exceed
.....#...........##.#......#.....0..#...........##.#......#...//line get doubled as if returning to beginning of the
.....#....##......##..#.#...........X....##......##..#.#......//same here
-1//to stop
so at the start, I move to the third index and down 1 which is to the next row and I check if that char is '#' if yes count++
so in this example- it moves three so the first row moves to ... then goes down to the next row which will be index 3 which in this case is .#. so the third is. and so on. and if it landed on # count++.
here's my code but it doesn't seem to work-
public static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
String a = "";//starts empty
int cnt = 0, b = 0;//cnt++ if '#', b helps us move 3 to the right each time
a = reader.nextLine(); //gets the string
if (b + 3 > a.length() - 1) {//checks that the length when moving 3 doesn't exceed string length
b = 0;// if it does exceed then go all the way to the left of the string
}
b += 3;//move right 3
a = reader.nextLine(); //get next line from the input
while (a != "-1") {//until there is -1 (to stop getting input) it continues to check
char c = a.charAt(b -
1);//takes whats at place b(-1 is because first index is 0 and not1) and note this is three to the right and after it moves down a row!// is line 23
if (c == '#' && a != "") {//checks if string isn't empty and if the char equals #
cnt++;//if yes count++
}
if (b + 3 > a.length() - 1) {//explained above
b = 0;
}
b += 3;
a = reader.nextLine();
}
System.out.println(cnt);
}
errors I get is the following:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 26
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
at java.base/java.lang.String.charAt(String.java:702)
at q.qq.main(Advent3.java:23)
help would be appreciated. let me know if something isn't clear or even how to improve:) thanks
code after talking in chat and trying to improve:
public class Advent3 {
public static Scanner reader= new Scanner(System.in);
public static void main(String[] args){
int b=4,cnt=0,line=1,s;
String str="";
char charsign;
str=reader.nextLine();
s=str.length();
str=reader.nextLine();
while(str!=""||str!="-1") {
line++;
s=str.length();
if(b%str.length()==0) {
charsign= str.charAt(10);
}
else {
charsign= str.charAt(b%str.length()-1);
}
if(charsign=='#') {
cnt++;
System.out.println(cnt);
}
b+=3;
str=reader.nextLine();
}
System.out.println(str);
System.out.println(cnt);
}
}
the code itself works and I think I'm very close but it doesn't print the right answer!
I'm stuck so help would be much-appreciated thanks!
public static int count(Scanner scan) {
int res = 0;
int col = -1;
String str;
boolean check = false;
while (!"-1".equals(str = scan.nextLine())) {
if (col >= str.length())
col %= str.length() - 1;
if (check && str.charAt(col) == '#')
res++;
col += 3;
check = true;
}
return res;
}
Demo:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(count(scan)); // 5
}
Input:
...#.#.......##....#.......#...
.#....#.##.#..#.......#.....##.
#..#...##.####..###.....#......
..#...##...#...#.#......#...#.#
.##.##.#...#.....#.##..##......
.#...#.#.##.###..#...#...#.....
.#..##..#....##.##....##....##.
..#...##....#..###........##...
.#..#..#.#....#.#...#.#......#.
.##.....#...#..#..#..#...###...
.#...#....#..#...........###...
.....#...........##.#......#...
.....#....##......##..#.#......
-1
Output:
...#.#.......##....#.......#...
.#0...#.##.#..#.......#.....##.
#..#.0.##.####..###.....#......
..#...##0..#...#.#......#...#.#
.##.##.#...1.....#.##..##......
.#...#.#.##.##2..#...#...#.....
.#..##..#....##.#3....##....##.
..#...##....#..###..3.....##...
.#..#..#.#....#.#...#.#3.....#.
.##.....#...#..#..#..#...#4#...
.#...#....#..#...........###.4.
..4..#...........##.#......#...
.....5....##......##..#.#......
-1
5
I am suppose to find odd numbers in an integer for HW. So countOddigtis(56781) should return( NOT PRINT ) 5 7 1. My approach was to convert the integer into a string and use that to return. Problems I am having are
Missing return statement error, even though I have a return statement in the if statement. Can someone explain what this error means and how to get past it?
It prints the wrong answer 49 for 56781 when I put return x; at the end of the method.
Can Java solve
stringn.charAt(x) % 2 != 0 considering I am might(NOT SURE) be comparing a string or char with an int?
P.S keep it simple, I don't much Java, I just started.
int countOddigits( int n )
{
int x = 0;
String stringn = Integer.toString(n);
while ( x <= stringn.length() - 1 )
{
if ( stringn.charAt(x) % 2 != 0 )
{
return stringn.charAt(x);
}
x++;
}
}
public void run()
{
System.out.printf("Odd number is %d\n: ", countOddigits(567981) );
}
You presumably don't want to return immediately when you find the first odd digit. You also need to convert the result back into an int (to match your return type). You can parse it with Integer.parseInt(String); and you can build that String with a StringBuilder. Also, you could make the method static. Like,
static int countOddDigits(int i) { // <-- camel case, that is camelCase
StringBuilder sb = new StringBuilder();
// for each char ch in the String form of i converted to a character array
for (char ch : String.valueOf(i).toCharArray()) {
if (Character.digit(ch, 10) % 2 != 0) {
sb.append(ch);
}
}
return Integer.parseInt(sb.toString());
}
Then, to test it, you can call it like
public static void main(String[] args) {
int oddDigits = countOddDigits(56781);
System.out.println(oddDigits);
}
Which outputs
571
This is the code that i have written for finding the smallest word in a string but whenever i try to run it in eclipse it shows me an (String index out of range -2147483648) error in nested while statement, that i had marked , i do not understand the cause of it since my program seems to be running well in the range i.e less than length of the input string.
Thanks in advance!!
import java.util.Scanner;
public class Minword {
public static String minLengthWord(String input){
// Write your code here
int count[]=new int[50],i,j=0,len=input.length();
String output = "";
for(i=0;i<len;i++)
{
if(input.charAt(i)!=' ')
{
count[j]++;
}
else
j++;
}
int minidx=0;
for(i=1;i<j;i++)
{
if(count[minidx]>count[i])
minidx=i;
}
int words=0;
i=0;
while(words<=minidx)
{
if(words==minidx)
{
***while(i<len && input.charAt(i)!=' ')***
{
output+=input.charAt(i);
i++;
}
}
else if(i<len && input.charAt(i)==' ')
words++;
i++;
}
return output;
}
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String input,output;
input=s.nextLine();
output=minLengthWord(input);
}
}
I have problems following your code, but to get the shortest word's length, you can use a Stream and min(). Your minLengthWord method could be like:
String f = "haha hah ha jajaja";
OptionalInt shortest = Arrays.stream(f.split(" ")).mapToInt(String::length).min();
System.out.println(shortest.getAsInt());
You are using the variable i, which is a signed int, so it ranges from -2147483648 to 2147483647.
The following case shows your problem:
i = 2147483647;
i++;
After the increment, i's value will be -2147483648 due to a int overflow. Check this question.
It seems you are getting a huge input, thus it is causing the problem.
Well, -2147483648 is the maximal integer + 1. You have a wrap around. The variable i got so big that it start on the negative side again.
You have to use a long if you want to process texts that are larger than 2 GB.
while(words<=minidx)
{
if(words==minidx)
{
***while(i<len && input.charAt(i)!=' ')***
{
output+=input.charAt(i);
i++;
}
}
else if(i<len && input.charAt(i)==' ')
words++;
i++;
}
Your problem is you when words and minidx are both 0, your outer while loop is always true and words are always equal to minidx, and i keeps increasing until reaches its maximum number.
you need to add break after your inner while loop and secondly, you need to change i<j to i<=j
Below is the corrected code:
int minidx = 0;
for (i = 1; i <= j; i++) { //-------------------------> change i<j to i<=j
if (count[minidx] > count[i])
minidx = i;
}
int words = 0;
i = 0;
System.out.println(minidx);
while (words <= minidx) {
if (words == minidx) {
while (i < len && input.charAt(i) != ' ') {
output += input.charAt(i);
i++;
}
break; //-------------------------> add break statement here.
} else if (i < len && input.charAt(i) == ' ') {
words++;
}
i++;
}
When I tried running your code with an input of "Hello World", minidx was 0 before the while loop. words is also 0, so words<=minidx is true and the loop is entered. words==minidx is true (they're both 0), so the if statement is entered. Because it never enters the else if (which is the only place words is changed), words is always 0. So the loop becomes an infinite loop. In the meantime, i just keeps growing, until it overflows and becomes negative.
Here's a version that makes use of Java 8's Stream API:
Remove all your code from minLengthWord Method and paste below code it will work and resolve your runtime issue too
List<String> words = Arrays.asList(input.split(" "));
String shortestWord = words.stream().min(
Comparator.comparing(
word -> word.length()))
.get();
System.out.println(shortestWord);
Problem: Check if the numbers in the string are in increasing order.
Return:
True -> If numbers are in increasing order.
False -> If numbers are not in increasing order.
The String sequence are :
CASE 1 :1234 (Easy) 1 <2<3<4 TRUE
CASE 2 :9101112 (Medium) 9<10<11<12 TRUE
CASE 3 :9991000 (Hard) 999<1000 TRUE
CASE 4 :10203 (Easy) 1<02<03 FALSE
(numbers cannot have 0 separated).
*IMPORTANT : THERE IS NO SPACES IN STRING THAT HAVE NUMBERS"
My Sample Code:
// converting string into array of numbers
String[] str = s.split("");
int[] numbers = new int[str.length];
int i = 0;
for (String a : str) {
numbers[i] = Integer.parseInt(a.trim());
i++;
}
for(int j=0;j<str.length;j++)
System.out.print(numbers[j]+" ");
//to verify whether they differ by 1 or not
int flag=0;
for(int j=0;j<numbers.length-1;j++){
int result=Integer.parseInt(numbers[j]+""+numbers[j+1]) ;
if(numbers[j]>=0 && numbers[j]<=8 && numbers[j+1]==numbers[j]+1){
flag=1;
}
else if(numbers[j]==9){
int res=Integer.parseInt(numbers[j+1]+""+numbers[j+2]) ;
if(res==numbers[j]+1)
flag=1;
}
else if(result>9){
//do something
}
}
This is the code I wrote ,but I cant understand how to perform for anything except one-digit-numbers ( Example one-digit number is 1234 but two-digit numbers are 121314). Can anyone have a solution to this problem?. Please share with me in comments with a sample code.
I'm gonna describe the solution for you, but you have to write the code.
You know that the input string is a sequence of increasing numbers, but you don't know how many digits is in the first number.
This means that you start by assuming it's 1 digit. If that fails, you try 2 digits, then 3, and so forth, until you've tried half the entire input length. You stop at half, because anything longer than half cannot have next number following it.
That if your outer loop, trying with length of first number from 1 and up.
In the loop, you extract the first number using substring(begin, end), and parse that into a number using Integer.parseInt(s). That is the first number of the sequence.
You then start another (inner) loop, incrementing that number by one at a time, formatting the number to text using Integer.toString(i), and check if the next N characters of the input (extracted using substring(begin, end)) matches. If it doesn't match, you exit inner loop, to make outer loop try with next larger initial number.
If all increasing numbers match exactly to the length of the input string, you found a good sequence.
This is code for the pseudo-code suggested by Andreas .Thanks for the help.
for (int a0 = 0; a0 < q; a0++) {
String s = in.next();
boolean flag = true;
for (int i = 1; i < s.length() / 2; i++) {
int first = Integer.parseInt(s.substring(0, i));
int k=1;
for (int j = i; j < s.length(); j++) {
if (Integer.toString(first + (k++)).equals(s.substring(j, j + i)))
flag = true;
else{
flag=false;
break;
}
}
if (flag)
System.out.println("YES");
else
System.out.println("NO");
}
I would suggest the following solution. This code generates all substrings of the input sequence, orders them based on their start index, and then checks whether there exists a path that leads from the start index to the end index on which all numbers that appear are ordered. However, I've noticed a mistake (I guess ?) in your example: 10203 should also evaluate to true because 10<203.
import java.util.*;
import java.util.stream.Collectors;
public class PlayGround {
private static class Entry {
public Entry(int sidx, int eidx, int val) {
this.sidx = sidx;
this.eidx = eidx;
this.val = val;
}
public int sidx = 0;
public int eidx = 0;
public int val = 0;
#Override
public String toString(){
return String.valueOf(this.val);
}
}
public static void main(String[] args) {
assert(check("1234"));
assert(check("9101112"));
assert(check("9991000"));
assert(check("10203"));
}
private static boolean check(String seq) {
TreeMap<Integer,Set<Entry>> em = new TreeMap();
// compute all substrings of seq and put them into tree map
for(int i = 0; i < seq.length(); i++) {
for(int k = 1 ; k <= seq.length()-i; k++) {
String s = seq.substring(i,i+k);
if(s.startsWith("0")){
continue;
}
if(!em.containsKey(i))
em.put(i, new HashSet<>());
Entry e = new Entry(i, i+k, Integer.parseInt(s));
em.get(i).add(e);
}
}
if(em.size() <= 1)
return false;
Map.Entry<Integer,Set<Entry>> first = em.entrySet().iterator().next();
LinkedList<Entry> wlist = new LinkedList<>();
wlist.addAll(first.getValue().stream().filter(e -> e.eidx < seq
.length()).collect(Collectors.toSet()));
while(!wlist.isEmpty()) {
Entry e = wlist.pop();
if(e.eidx == seq.length()) {
return true;
}
int nidx = e.eidx + 1;
if(!em.containsKey(nidx))
continue;
wlist.addAll(em.get(nidx).stream().filter(n -> n.val > e.val).collect
(Collectors.toSet()));
}
return false;
}
}
Supposed the entered string is separated by spaces, then the code below as follows, because there is no way we can tell the difference if the number is entered as a whole number.
boolean increasing = true;
String string = "1 7 3 4"; // CHANGE NUMBERS
String strNumbers[] = string.split(" "); // separate by spaces.
for(int i = 0; i < strNumbers.length - 1; i++) {
// if current number is greater than the next number.
if(Integer.parseInt(strNumbers[i]) > Integer.parseInt(strNumbers[i + 1])) {
increasing = false;
break; // exit loop
}
}
if(increasing) System.out.println("TRUE");
else System.out.println("FALSE");
A sample input of 12345 should return 12,345. I have it figured out i think. Only problem is the string I get is reversed (543,21). Now i know there's ways to reverse a string pretty easily but that's more complexity to the running time so I was wondering if there was a straightforward way to do it within the auxiliary itself?
public void print(int n){
String number = Integer.toString(n);
StringBuilder answer = new StringBuilder();
if(number.length() > 3){ //Only worry about adding commas if its more than three digits
printAux(number, answer, 1, number.length()-1);
System.out.println(answer);
}
}
private void printAux(String s, StringBuilder answer, int count, int index){
if(index < 0){
return;
}
else{
//If the counter is at the 4th index meaning it has passed three digits
if(count%3 == 1 && count > 3){
answer.append(",");
index = index + 1;
count = 0;
}
else{
answer.append(s.charAt(index));
}
printAux(s, answer, count + 1, index - 1);
}
}
Something simpler
public static void print(String s) {
out.print(s.charAt(0));
if (s.length() == 1) out.print("\n");
else {
if (((s.length()-1) % 3) == 0) out.print(",");
print(s.substring(1));
}
}
Explanation:
always print the 1st character
if there is no more character, print CR
if there is at least one character to process, check if the length of what to process is a multiple of 3, if yes print a ","
and call recursively print with the string minus the 1st character
You can can use StringBuilder.reverse() to reverse a String in one line like
String str = "abc";
str = new StringBuilder(str).reverse().toString();
But you could also use printf1. Something like,
public static void print(int n) {
System.out.printf("%,d%n", n);
}
public static void main(String[] args) {
int num = 123456789;
print(num);
}
Output is (as requested)
123,456,789
1See also The Java Tutorials - Formatting Numeric Print Output for more options.
You can use the following DecimalFormat to get the job done.
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));