So , I am trying to create a program which calculates the score of an exam . What we have to do is give a pattern as a string consisting X's and 0's i.e 000XXX000XXX, where the value of 'X' is 0 and the value of each zero is 1 and for every consecutive '0' the value increases by 1 . If suppose there are 2 or more consecutive 0's and then an 'X' the value of '0' is reset to 1.if the program seems common to you , then , yes this is a problem from an OJ and it was given to me by a senior from my university to solve.Now the thing is I have figured out how the code works and solved the problem.But there seems to be an issue in the code.
package javaapplication4;
import java.util.Scanner;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T, score = 0, f = 0, g = 0;
String str;
int len;
T = sc.nextInt();
for (int i = 1; i <= T; i++) {
str = sc.nextLine();
len = str.length();
for (int j = 0; j < len; j++) {
if (str.charAt(j) == '0') {
f++;
score = score + f;
}
else if(str.charAt(j) == 'X')
{
f = 0;
score = score + g;
}
}
System.out.println(score);
}
}
}
As you can see from the code , I first give an Input for the number of test cases and as soon as I press enter , the code displays the value of score (which is 0) automatically without doing any think inside the for loop.
I have rechecked all the curly braces, but I cannot find the bug in the code. I would be happy if I could get some help.
Output:
4
0
The sc.nextInt() causes the sc.nextLine() to be triggered so you get the output of a empty string that's why it's zero, by using sc.nextLine() for input of your test case number you can prevent this:
int score = 0;
System.out.println("Enter test case:");
int testCase= Integer.parseInt(sc.nextLine());
for (int i = 1; i <= testCase; ++i)
{
System.out.println("Enter pattern:");
String str = sc.nextLine();
for (int j = 0; j < str.length(); j++)
{
if (str.charAt(j) == '0')
{
score += 1;
}
else if (str.charAt(j) == 'X')
{
score += 0;
}
}
System.out.println(score);
score = 0; // reset score to zero for the next test case
}
See this link regarding the sc.nextInt() issue : Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
Related
I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.
I'm writing a java code currently for class and I'm trying to figure out how to implement a run length encoding on a user input. The main problem I'm having it with comparing the first letter with the next and that letter with the next and so on to see if they're the same letter. Currently I have:
System.out.print("Enter a string: ");
String s1 = reader.nextLine();
int sum = 0;
char ast = '*';
//System.out.println("Run length encoded version of string: ");
for (int counter = 0; s1.charAt(counter) <= s1.length()-1; counter++) {
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
if (sum >= 4) {
System.out.print(ast + s1.charAt(counter) + sum);
}
else {
System.out.print(s1.charAt(counter));
}
}
I know where the big problem comes from in this and why it doesn't work but, namely from the
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
segment as it just goes infinitely. Is there a proper way to do this? The professor mentioned it can be done without loops and while I can see it being possible I can't see it being short. Any help would be appreciated, thanks!
String str="ayyusaab";
char[] ch=str.toCharArray();
for(int i=0;i<ch.length-1;i++){
for(int j=i+1;j<ch.length-1;j++){
if(ch[i]==ch[j]) {
System.out.println(ch[i]+" at Index "+i +"with j at "+j);
}
}
}
I'm currently working on an assignment for school and the objective is to have the user input n amount of lines and then print them in reverse.
For example:
"Please enter number of lines: "
3
"Please enter the lines: "
Hi
Hey
Howdy
Desired Output:
Howdy
Hey
Hi
My output:
H
o
w
d
y
H
e
y
H
i
I'm not sure what's wrong and I'd really like some help, here is my code:
import java.util.Scanner;
public class ReverseOrder {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the number of lines: ");
int numberOfLines = kb.nextInt() + 1;
String inputLines[] = new String[numberOfLines];
System.out.println("Please enter the lines: ");
for (int i = 0; i < numberOfLines; i++) {
inputLines[i] = kb.nextLine();
}
System.out.println("Lines in reverse: ");
for (int i = numberOfLines - 1; i >= 0; i--) {
for (int j = 0; j <= inputLines[i].length() - 1; j++) {
System.out.println(inputLines[i].charAt(j));
}
}
kb.close();
}
You are printing each character with an end of line character by calling println() with your current two for loops. This is one step too many.
Since you already have the entire string, you can simply print the strings in reverse order like so using the println() function
for(int i = numberOfLines - 1 ; i>=0; i--){
System.out.println(inputLines[i]);
}
#Kody
I'm not sure what you have to do in your code but:
If you need just print each line in a reverse order, you can do this:
System.out.println("Lines in reverse: ");
for (int i = numberOfLines - 1; i >= 0; i--) {
System.out.println(inputLines[i]);
}
The method println will create a new line for you.
I'm working on a code in which an input String is taken and an input character is taken. the code will calculate the percentage occurrence of that character in that String. the code is given below:
import java.util.Scanner;
class apple{
public static void main(String args[]){
int i,j,l=0;
float m;
char k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String");
String str = in.nextLine();
j=str.length();
System.out.println("Enter the character to be found");
char s = in.next(".").charAt(0);
for(i=0;i<=j;i++){
k = str.charAt(i);
if(k == s){
l++;
}
}
m= l/j;
m=m*100;
System.out.println("percent character in String is "+m);
}
}
Change your loop to
for(i = 0 ;i < j ; i++)
Otherwise, if your String has a length of 4 (so the last index is 3), it will try to reach index 4 and throw an Exception.
You are doing this:
for (i = 0; i <= j; i++) {
and this is throwing an java.lang.StringIndexOutOfBoundsException:
because you are not considering that the element goes from 0 to lengt-1
instead you should do:
for (i = 0; i < j; i++) {
Edit your for-loop to for (i=0;i<j;i++). We can not access the element at array size position because Java array uses 0-based index
The first character of a String is '0', the last is yourString.length()-1, so change your loop to
for( i = 0 ; i < j ; i++ ){
k = str.charAt(i);
if(k == s){
l++;
}
}
It'll work ;)
Basically I'm trying to make a program to accept an integer between 1 and 10 and also an alphabetic character. It then outputs an appropriate pattern based on this value as a maximum width
For example a user enters an integer of 5 and a letter X the program prints out:
x
xx
xxx
xxxx
xxxxx
I can't seem to get it to print out anything, below is what I've got so far.. any tips are extremely appreciated!
import java.util.*;
public class pattern {
public static void main(String[] args) {
int New1 = 1, Linecounter = 1;
Scanner sc = new Scanner(System.in);
int Number = sc.nextInt();
if (Number >= 1 && Number <= 10) {
Number = New1;
}
else{
System.out.println("Error: Enter a number between 1 and 10");
}
Scanner keyboard = new Scanner(System.in);
char letter = keyboard.next().charAt(0);
for (New1 = 1; New1 <= 10; New1++) {
for (letter = (char) Linecounter; letter <= 10; letter++) {
System.out.print("" +letter+ "");
}
System.out.println();
}}}
First off:
if (Number >= 1 && Number <= 10) {
Number = New1;
}
Sets Number = 1. After this code executes, both Number and New1 are equal to 1. You want something where Number is set to the input. Now the loops need work. You should have something like this:
for (int i = 1; i <= Number; i++) { //1 through Number
for (int j = 1; j <= i; j++) {
System.out.print(letter); //Print letter i times
}
System.out.print("\n"); //New line
}
Is it something like this, you're searching for?
int x = 5;
char letter = 'x';
for (int i = 0; i <= x; i++)
{
for (int j = 0; j < i; j++)
{
System.out.print(letter);
}
System.out.println();
}
The above outputs
x
xx
xxx
xxxx
xxxxx
This seems like homework, so I'll just bring you pseudo code. The idea is to do something like this:
for i in 1..x do
for j in 1..i do
print ('*')
end
println (''
end
(in fact, if you change the println for puts this becomes a valid Ruby script).
Anyway, the key here is: you need as many asterisk as lines entered by the user. As long as you print an asterisk in the inner loop without printing a newline, and call println in your outer loop, you are ok to go.
It is also important that you iterate up to the wanted value in the outer loop, but only up to the New1 variable in the inner loop.
Try this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Integer: ");
int userInt = scan.nextInt();
System.out.print("Letter: ");
String userLetter = scan.next();
String letter = "";
for (int i = 0; i <= userInt; i++) {
System.out.println(letter);
letter += userLetter;
}
}
This doesn't limit the input to be between 1-10, you can add a little if statement for that.