java regex loop are not running properly - java

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringInteger {
public static void main(String[] args) {
System.out.println("Enter no. of times input numbers will be given : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int index = 0, index1 = 0;
int girl[] = new int[1000];
int boy[] = new int[1000];
for (int i = 1; i <= n; i++) {
String s = sc.next();
Pattern mypattern = Pattern.compile("[0-9]+");
Matcher mymatcher = mypattern.matcher(s);
while (mymatcher.find()) {
if (i % 2 != 0) {
girl[index] = Integer.valueOf(mymatcher.group());
index++;
} else {
boy[index1] = Integer.valueOf(mymatcher.group());
index1++;
}
}
}
for (int j = 0; j < index; j++) {
System.out.print(girl[j] + " ");
}
}
}
Why loop are not running upto its limit?

For loop runs correctly for the no. of times i.e. n.
You should format your code, Java class name should be CamelCase and without underscore and do add System.out.println to help you understand debugging and program makes more logical sense.
It seems like your program is expecting a number for which user can enter numbers.
There are 2 arrays i.e. girl and boy. If the number is odd then then it is added to girl array and if the number is even then it is added to boy array.
Finally girl array is printed.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringInteger {
public static void main(String[] args) {
System.out.println("Enter no. of times input numbers will be given : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int index = 0, index1 = 0;
int girl[] = new int[1000];
int boy[] = new int[1000];
for (int i = 1; i <= n; i++) {
String s = sc.next();
Pattern mypattern = Pattern.compile("[0-9]+");
Matcher mymatcher = mypattern.matcher(s);
while (mymatcher.find()) {
if (i % 2 != 0) {
girl[index] = Integer.valueOf(mymatcher.group());
index++;
} else {
boy[index1] = Integer.valueOf(mymatcher.group());
index1++;
}
}
}
for (int j = 0; j < index; j++) {
System.out.print(girl[j] + " ");
}
}
}
Sample Run:
Enter no. of times input numbers will be given :
4
10
11
12
13
10 12

Related

Java Program to Enter a sentence and print the longest word [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 months ago.
Improve this question
This a program to enter a sentence and print the longest word using substring()
Here, I have used the 1st loop to extract each word from the sentence and find the length of the longest word.
In the 2nd Loop, its purpose is it to extract and print the word that matches the length which was found out in the 1st loop and stored in the "longestLength" variable.
I am getting an error when i compile the following code:
import java.util.*;
public class Program {
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() > longestLength)
longestLength = st.length();
i1 = i;
}
}
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() == longestLength) {
System.out.println("Longest Word : " + st);
break;
}
i1=i;
}
}
}
}
Here you don't need to use for loops for just finding the longest word.
Just remove the for loops and add the following lines below that.
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
String longest = Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null);
System.out.println(longest);
YOUR FINAL CODE WILL BE:
import java.util.*;
public class Program {
public static void main(String[] args) {
String s;
int longestLength = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
String longest = Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null);
System.out.println(longest);
}
}
It will print the longest word. Hope it will be helpful to you.
There is an alternate easy method to split sentence using delimter using String.spilt(delimiter) funciton.
Below code is an working example for your task
public class Test {
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
String maxString = "";
for(String string : s.split(" ")){
maxString = maxString.length() > string.length() ? maxString : string;
}
System.out.println("The max lengthed string is : "+maxString);
}
}
Your issue is due to i1 has not be resetted to 0 hence the old loop value if i1 is there hence the issue
The solution is given below:
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() > longestLength)
longestLength = st.length();
i1 = i;
}
}
i1=0;
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() == longestLength) {
System.out.println("Longest Word : " + st);
break;
}
i1=i;
}
}
}

Read, store and print user input

I have to get 4 user input from the user one by one on the next line like
Sample input:
65
66
67
68
Then the output has to displayed like
You have entered:
65-A
66-B
67-C
68-D
the program i have return is this:
import java.util.Scanner;
public class ASCII {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the digits:");
int no = sc.nextInt();
char ch= (char) no;
System.out.println(no + "-" + ch);
}
}
the one thing could not get is the 4 input for the user could someone help with that
You should loop it;
int[] numbers = new int[4];
for (int i = 0; i < 4; i++) {
numbers[i] = sc.nextInt();
}
numbers[n-1] will return number in your case 0 < n < 5;
and you can create another loop to print them.
chars[] characters = {'A','B','C','D'};
for (int i = 0; i < 4; i++) {
System.out.println(Integer.toString(numbers[i]) + characters[i]);
}
for loops works like;
for (DoAtStart; Condition; DoAtEndOfARepeat) {
}
This would work for you :
public class ASCII {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the digits:");
int array[]=new int[4];
for(int i=0; i<4;i++) {
int no = sc.nextInt();
array[i]=no;
}
System.out.println("You have entered:");
for(int j=0;j<array.length;j++) {
char ch= (char) array[j];
System.out.println(ch+"-"+array[j]);
}
}
}

Java: Printing trailing spaces

I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:
4
1 4 3 2
The code will need to reverse the second input to the following:
2 3 4 1
My solution is as follow:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
System.out.print(arr[reverse_i]);
if(reverse_i != 0){System.out.print(" ");}
}
}
My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.
The easy way to reverse a string is using the StringBuilder class:
One option is to remove the spaces at the end of the string eg. remove last char
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
Another option is to check whether you are at the last arr_i of your loop.
If so, then don't add a space
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
if (arr_i != 3
sb.append(" ");
}
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
First reverse the array and then print it with a for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++)
{
arr[arr_i] = in.nextInt();
}
for(int i = 0; i < arr.length / 2; i++)
{
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+" ");
}
}
}
It is all about output formatting. You may use this examples and become familiar with all possible approaches.
Your code can be improved in next two ways :
1) Use \t instead of Empty Space (\t is a tabulation)
2) Create a constant with output format like this private static final String output = "%d " and use it in output line like this : String.format(output, number) where number is your number that should be printed.

program that reads integers between 1 and 100 and counts the occurrence of each

Write a program that reads integers between
1 and 100 and counts the occurrence of each (you should store the numbers in an array). Output should be in ascending order. Assume the input ends when the user enters a 0.
Hi guys, I know that this question has been posted before, perhaps a lot of times, but as I am a complete beginner at java, I don't completely understand the complexity of the codes that are posted. I just started taking Java classes, and would appreciate if you could help me figure out how to get my program to output the correct occurrences at the end. I'm so close to getting the answer but I can't figure it out for the life of me!! Thanks in advance!
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
//declarations
int [] myArray = new int [100];
int input = 5;
Scanner keyboard = new Scanner(System.in);
//input and processing
System.out.println("Please enter integers between 1 and 100 (enter 0 to stop): ");
while (input != 0)
{
input = keyboard.nextInt();
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] = input;
}
}
}
//output (This is where I need help!!!!)
for (int k = 0; k < myArray.length; k++)
{
if (myArray[k] != 0)
{
System.out.print(k + " occurs " + myArray[k] + " time");
if (myArray[k] > 1)
{
System.out.println("s");
}
else
System.out.println("");
}
}
keyboard.close();
}
}
You are storing the number entered by the user in the array. Instead, you should store a counter in each position of the array for the corresponding integer. When the user inputs a number, you should increase the corresponding counter.
The second part of your code (output results) seems ok. It is the first one that needs fixing.
I think the first for loop should be something like this:
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] += 1;
}
}
}
This should store add 1 to the array everytime the numbers occurs.
hey this my source code that worked out or me.
package test2;
import java.util.Arrays;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// ask for user to input numbers
System.out.println("Enter some integers between 1 and 100 (and 0 when done): ");
int[] myArray = new int[1000];//create a new array for user inputs
int number;//variable for user inputs
int count = 0;
do
{
number = input.nextInt();
myArray[count] = number;
count++;
}
while (number != 0);
int[] mySort = new int [count - 1]; //create a new array with only the numbers
for(int i = 0; i< (count-1); i++) { //get the array until 0th number into new
mySort[i] = myArray[i];
}
java.util.Arrays.sort(mySort);// sort the array in ascending order
int n = 0;
for(int i = 0; i < mySort.length; i++) {//check if the number have checked before
int occurance = 0;
if(n >= mySort[i]) {
continue;
}
else {
n = mySort[i];//if a new number found do the calculation+
for (int j=0; j<mySort.length; j++)
if (n == mySort[j])
occurance++;
System.out.print(n + " occurs " + occurance );
{
if (occurance == 1) {
System.out.println(" time.");
}
else {
System.out.println(" times.");
}
}
}
}
}
}

ArrayList<Integer>, trying to find average of entered values

Trying to find the average of the integers entered as input into the list.
Cant figure out how, im getting an error saying that it can't find symbol in
in the line total = total + in;
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;
public class Lists
{
public static void main(String[] args)
{
PrintStream print = new PrintStream(System.out);
Scanner scan = new Scanner(System.in);
List<Integer> bag = new ArrayList<Integer>();
print.println("Enter your integers");
print.println("(Negative=sentinel)");
int total = 0;
int count = 0;
for (int in = scan.nextInt(); in > 0; in = scan.nextInt());
{
total = total + in;
count = count + 1;
}
double x = total / count;
print.println("The average is: " + x);
}
}
also, is there an easy way to output the numbers above average divided with a comma?
Remove the semi-colon after the for loop:
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())
The reason in is not defined for the compiler is that the semi-colon would de-scope its definition by acting as an empty body of the for loop.
Remove ; from your loop.
for (int in = scan.nextInt(); in > 0; in = scan.nextInt());
change to
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())
You shouldn't have ; after for loop...
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())//remove ; here
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
You have added semicolon ; so it's become empty body for for loop. you have to remove the semicolon after for (int in = scan.nextInt(); in > 0; in = scan.nextInt()) line in your code.
Modified Code : I am providing code after modification.
public class Lists
{
public static void main(String[] args)
{
PrintStream print = new PrintStream(System.out);
Scanner scan = new Scanner(System.in);
List<Integer> bag = new ArrayList<Integer>();
print.println("Enter your integers");
print.println("(Negative=sentinel)");
int total = 0;
int count = 0;
for (int in = scan.nextInt(); in > 0; in = scan.nextInt()){
total = total + in;
count = count + 1;
}
double x = total / count;
print.println("The average is: " + x);
}
}
The above code requires two changes:
1.You need to remove the semicolon after for loop which is making loop useless and all the iterations you want to do won't take place.
2.The second change is you need to cast one of the variables total or count to double to avoid truncation else your results will always be integers.
The modified code is as follows:
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;
public class Lists
{
public static void main(String[] args)
{
PrintStream print = new PrintStream(System.out);
Scanner scan = new Scanner(System.in);
List<Integer> bag = new ArrayList<Integer>();
print.println("Enter your integers");
print.println("(Negative=sentinel)");
int total = 0;
int count = 0;
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())
{
total = total + in;
count = count + 1;
}
double x = (double)total / count;
print.println("The average is: " + x);
}
}

Categories

Resources