Ascending a String input of numbers in java - java

I am working on a program where user can input random numbers and when user give -1 the loop will break and the entered numbers will be displayed
Example:
Enter a Number: 32
Enter next Number: 1243
Enter next Number: 123
Enter next Number: 76
Enter next Number: -1
Thank You. You have entered 32, 1243, 123, 76
Now whatever number is entered it will be displayed in ascending order
----Ascending order -----
[32,76,123,1243]
Now i have completed the following but the to get exact result the user need to enter
->0032
->0076
->0123
->1243
Then i am getting the exact result
[0032, 0076, 0123, 1234]
Then only my sorting is working fine otherwise it is like
[ 123, 1243, 32, 72]
Now how to solve this ?
package Testx;
import java.util.Arrays;
import java.util.Scanner;
public class Test7Ctr{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner user = new Scanner(System.in);
String user_input = "";
String holdv="";
String holdvx="";
String ascend="";
//AsveNd(user_input);
try
{
int b =0;
do
{
System.out.print("Enter next number:");
user_input = user.nextLine();
int x= Integer.valueOf(user_input);
if (x != -1)
{
holdv=user_input;
holdvx+=holdv+",";
ascend+=holdv+" ";
b++;
}
else
{
System.out.println("THANK YOU FOR ENTERING= "+holdvx);
break;
}
}
while(b <= 100);
{
}
String[] numbers=ascend.split("\\s");
for(String numb:numbers)
{
int intarray[] = new int[numbers.length];
Arrays.sort(numbers);
//break;
}
System.out.println("---Ascending order---");
System.out.println(Arrays.toString(numbers));
}
catch(Exception e)
{
}
}
}

You are sorting strings rather than numbers. This makes your sort work in lexicographic order instead of plain ascending order.
So to fix your problem, simply add Integers and not Strings. You can even parse a String to an Integer using Integer.parseInt().
Also, there is no need to call sort every time you insert a new number, but just once in the end. That adds a lot of overhead to your process.

You can get the proper integer sorting with the following:
String[] numbers = ascend.split("\\s");
int intarray[] = new int[numbers.length];
int i = 0;
for (String numb : numbers)
{
// convert the String to an int
intarray[i++] = Integer.parseInt(numb);
}
Arrays.sort(intarray); // sort the int array, not the String array
System.out.println("---Ascending order---");
System.out.println(Arrays.toString(intarray));
Side Note:
Your do/while loop would be better written as:
int x = 0;
do
{
System.out.print("Enter next number:");
user_input = user.nextLine();
x = Integer.valueOf(user_input);
if (x != -1)
{
holdv = user_input;
holdvx += holdv + ",";
ascend += holdv + " ";
}
} while (x != -1);
System.out.println("THANK YOU FOR ENTERING= " + holdvx);
You don't need the int b
You don't need the else statement in the loop. Just have the loop terminate when x is -1.
Also, you had an empty block after the while (...); That is not doing anything. The while portion of a do/while loop has no body.

You are sorting the "Strings" and not the "numbers". Scan those inputs as number, put them to a dynamic list (and not a static sized array) and then sort the list of numbers (and not of string)

Related

How to count the Strings, numbers, and doubles in a script from the users' input (Scanner) in java?

I'm a beginner and I have tried a few different ways from the stuff that I have learned from other people's questions, but I think my problem with the following problem is that I can't figure out the logic of my code. If someone can suggest a solution with explaining the logic of the codes, I would greatly appreciate it.
I'm supposed to create a method in the format of method() that will prompt the user to enter a script that includes String, numbers, and doubles. The method should count the number of Strings, numbers, and doubles and prints out the list of the string, numbers and doubles. I have got the part that the method prints the list of the strings, numbers and doubles, but it seems I can't get the counter to count them. I have got this so far:
import java.util.Scanner;
public class Games {
private Scanner input;
public Games() {
input = new Scanner(System.in);
}
public void textParser() {
System.out.println("Enter a Script");
int intCount = 0;
int dblCount = 0;
int strCount = 0;
while(input.hasNext()) {
if(input.hasNextInt()) {
int num = input.nextInt();
System.out.println(num);
intCount++;
}else if(input.hasNextDouble()) {
double value = input.nextDouble();
System.out.println(value);
dblCount++;
}else {
String oneWord = input.next();
System.out.println(oneWord);
strCount++;
}
}
System.out.println("Number of integers: " + intCount);
System.out.println("Number of doubles: " + dblCount);
System.out.println("Number of strings: " + strCount);
}
public static void main(String[] args) {
Games demo = new Games();
demo.textParser();
}
}
Example of expected inputs and outputs:
Enter a Script
32 quick brown foxes jump over 65 lazy dogs and few doubles are 43.3
and 76.9
32
65
Number of integers: 2
43.3
76.9
Number of doubles: 2
quick
brown
foxes
jump
over
lazy
dogs
and
few
doubles
are
and
Number of strings: 12
Actual output:
32
65
43.3
76.9
quick
brown
foxes
jump
over
lazy
dogs
and
few
doubles
are
and
Near the beginning, you say while(scanner.hasNext(). This means, that all the code in the loop will be excecuted pretty much as long as the program runs.
You have put the statements that print the counters outside of the loop, and designed your code in a way, that you will never leave that loop.
So you need some kind of exit condition. Let's say, if one of the strings is exit, you exit the loop and print the counters:
while (input.hasNext()) {
if (input.hasNextInt()) {
// ...
} else if (input.hasNextDouble()) {
// ...
} else {
String oneWord = input.next();
System.out.println(oneWord);
strCount++;
if (oneWord.equals("exit")) {
input.close();
break;
}
}
}
or, if you don't want to have to put "exit" in there, do this:
int intCount = 0, doubleCount = 0, stringCount = 0;
while (input.hasNextLine()) {
String[] segments = input.nextLine().split(" ");
for (String segment : segments) {
System.out.println(segment);
try {
int asInt = Integer.parseInt(segment);
intCount++;
} catch (NumberFormatException e) {
try {
double asDouble = Double.parseDouble(segment);
doubleCount++;
} catch (NumberFormatException e2) {
stringCount++;
}
}
}
System.out.println("Number of integers: " + intCount);
System.out.println("Number of doubles: " + doubleCount);
System.out.println("Number of strings: " + stringCount);
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix) or at the end of the file if you use < style redirection.
You need some kind of exit condition
if (oneWord.equals("exit")) {
input.close();
break;
}
Another approach after giving your input Ctrl+Z it will send EOF.

How to filter certain values of numbers from a string and return the rest

I need to create a method that takes a string as an input, like "I have 2456 balloons in 37 wilderness" and if n is set to 3 and "more" is set to false, the method would return "I have 2 balloons in wilderness". If more was set to true, it would return "I have 456 balloons in 7 wilderness"
I have been playing around with the filtering part quite a bit, but I don't know how to put the rest of this method together. Here is what I have come up with so far:
public class Test1
{
public static void main(String [] args)
{
List<Integer> lst= new ArrayList<Integer>();
//Take user input any number of times based on your condition.
System.out.println("Please enter a number :");
Scanner sc= new Scanner(System.in);
int i= sc.nextInt();
if(i==0 || i==1 || i==2 ||i==3)
{
lst.add(i);
}
//Go back
}
}
Or I could use something like this:
int input;
do {
input = sc.nextInt();
} while (input < 0 || input > 3);
I'm pretty new to Java, so progress on this task has been slow
How can I get this method to save the letters and filter numbers depending on the two values (a number and true/false for more)?
Here is a simple solution with explanation.
Take note that we used a very straightforward approach but a lot of validations are still needed. Also, there are shorter solutions but this is the one I wrote so that it's clearer for people new in Java.
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter your string: ");
String strInput = sc.nextLine();
System.out.println("Enter n: ");
int n = sc.nextInt();
System.out.println("Do you want more? (Y/N)");
char more = sc.next().charAt(0);
String result = "";
// Loop through all the characters in the String
for(char c : strInput.toCharArray()) {
// Check if the character is a number
// If not, just append to our result string
if(!Character.isDigit(c)) {
result += c;
} else {
// Converts character to the number equivalent value
int numValue = Character.getNumericValue(c);
// If more is 'Y', we check if it's greater than the number and append
// else if more is 'N', we check if the value is less than n then append.
// Otherwise, do nothing.
if (more == 'Y' && numValue > n) {
result += c;
} else if (more == 'N' && numValue < n) {
result += c;
}
}
}
System.out.println(result);
}

Cannot do the sum of numbers using a comma and string tokenizer

I have a program but I dont know specifically what my mistake is or how to fix it: The question is:
Write a program that asks the user to enter a series of numbers separated by commas.
The program should calculate and display the sum of all the numbers.
For example, if I enter 4,5,6,7, the sum displayed should be 22.
This is what I have so far:
import java.util.Scanner;
public class SumAll {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userNumber;
String sum = null;
//get numbers from user and store
System.out.println("Enter numbers seperated by coma's: ");
userNumber = keyboard.nextLine();
String[] tokens = userNumber.split("[, ]");
for (int i = 0; i < tokens.length; i++) {
sum = tokens.length[i++]; //showing me error here. Its written array required but int //found.
}
System.out.println("Sum is: " + sum);
}
}
Thank you very much for the help.
Sum should be an int
int sum = 0;
Your for loop should be
for (int i = 0; i < tokens.length; i++) {
sum += Integer.parseInt(tokens[i]);
}
Because it should be:
sum += Integer.parseInt(tokens[i]);
There are several things wrong with this one line of code.
sum = tokens.length[i++];
You can't index the length of the array like that. Just index the array (see below).
The for loop is already incrementing i. You don't need to do it again.
You need to convert the token to an integer before you can add it to the sum.
You need to add the new value to the sum, not replace the old sum.
Try this instead:
sum += Integer.parseInt(tokens[i]);
You'll also need to make sum an integer. Instead of
String sum = null;
you need
int sum = 0;
I know I am more than 2 years late but I started learning Java not too long ago and would like to share my solution. :) I used the StringTokenizer class. I hope this helps someone out there in 2017 and onward.
import java.util.Scanner;
import java.util.StringTokenizer;
public class SumOfNumbersInString {
public static void main(String[] args) {
// Create a Scanner object
Scanner keyboard = new Scanner(System.in);
// Get user input
System.out.print("Enter a series of numbers seperated by commas\n> ");
String input = keyboard.nextLine();
// Display sum by calling the getSum method
System.out.println("SUM: " + getSum(input));
}
/**
*
* #param input with the format --> (#,#,#,#)
* #return sum of numbers in the input
*/
public static int getSum(String input) {
// Declare and initialize the sum accumulator variable
int sum = 0;
// Create a StringTokenizer object
// The string to be tokenized is passed as 1st parameter
// The "," that separates tokens/numbers is the 2nd parameter
StringTokenizer stringTokenizer = new StringTokenizer(input, ",");
// The hasMoreTokens method of the StringTokenizer class returns true if there are more tokens left in the string
// Otherwise, it returns false
while (stringTokenizer.hasMoreTokens()) {
// While the string has another token (number), parse the number to an integer and add its value to sum
sum += Integer.parseInt(stringTokenizer.nextToken());
}
// Return sum's value to the method call
return sum;
}
}
OUTPUT
Enter a series of numbers seperated by commas
> 4,5,6,7
SUM: 22
/** #author Jerry Urena **/
public static void main(String[] args)
{
String userinput;
int total = 0;
//keyboard function
Scanner keyboard = new Scanner(System.in);
//Ask for input
System.out.print("Please enter a series of numbers separated by commas " );
//Get user input
userinput = keyboard.nextLine();
//Split numbers
String[] numbers = userinput.split("[,]");
//String loop
for (String number : numbers)
{
//Sum of numbers
total += Integer.parseInt(number);
}
//Print results
System.out.println("Total: " + total);
}

keep tracking of each token

I need to solve the following problem: Write a method named tokenStats that accepts as a parameter a Scanner containing a series of tokens. It should print out the sum of all the tokens that are legal integers, the sum of all the tokens that are legal real numbers but not integers, and the total number of tokens of any kind. For example, if a Scanner called data contains the following tokens:
3 3.14 10 squid 10.x 6.0
Then the call of tokenStats(data); should print the following output:
integers: 13
real numbers: 9.14
total tokens: 6
If the Scanner has no tokens, the method should print:
integers: 0
real numbers: 0.0
total tokens: 0
So, this is my question. I have tried to use
while (input.hasNext()) {
if (input.hasNextInt()) {
and this creates an infinite loop,
but if I use
while (input.hasNext()) {
input.next();
if (input.hasNextInt()) {
I lose my first token if it is an int...
what should I do?
I suggest you check this way .. which cover all your scenario
int totalint =0;
float totalfloat=0 ;
int count=0;
while(input.hasNext())
{
String next = input.next();
int n; float f;
try{
if(next.contains(".")
{
f= Float.parseFloat(next);
totalfloat += f;
}
else{
n= Integer.parseInt(next);
totalint +=n;
}
}
catch(Exception e){ /*not int nor a float so nothing*/ }
count++;
}
In order to determine the amount of Integers in your file I suggest doing something like this
Add the following variables to your code
ArrayList<Integer> list = new ArrayList<Integer>();
int EntryCount = 0;
int IntegerCount =0;
Then when looking through the file inputs try something like this were s is an instance of a scanner
while (s.hasNext()) {
if(s.hasNextInt() == true){
int add =s.nextInt();
System.out.println(add);
list.add(add);
IntegerCount++;
}
EntryCount++;
}
Then in order to figure out the sum of all integers you would loop through the array list.
public static void tokenStats(Scanner input) {
int integers = 0;
double real = 0.0;
int tokens = 0;
while (input.hasNext()) {
if (input.hasNextInt()) {
integers+= input.nextInt();
} else if (input.hasNextDouble()) {
real+= input.nextDouble();
} else {
input.next();
}
tokens++;
}
System.out.println("integers: " + integers);
System.out.println("real numbers: " + real);
System.out.println("total tokens: " + tokens);
}

Inputting a number then reversing it

Ok so I wrote a program which asks user to input a number and then reverse it. I was successful in it however the program does not reverses numbers that end with a 0. for example if i enter 1234 it will print out 4321 however if i input 1200 it will only output 21. I tried converting the number that is to become output into string. Please help me understand where I am doing it wrong. Just remember I am a beginner at this :). Below is my code.
import java.util.*;
public class ReverseNumber
{
public static void main (String [] args)
{
Scanner n = new Scanner(System.in);
int num;
System.out.println("Please enter the number");
num = n.nextInt();
int temp = 0;
int reverse = 0;
String str = "";
System.out.println("The number before getting reversed " + num);
while (num != 0)
{
temp = num % 10;
reverse = reverse*10 + temp;
num = num/10;
str = Integer.toString(reverse);
}
//String str = Integer.toString(reverse);
System.out.println("The reversed number is " + str);
}
}
You're storing your reversed number as an int. The reverse of 1200 is 0021, but that's just 21 as an int. You can fix it by converting each digit to a string separately.
The problem is that you're calculating the reversed value as a number and, when it comes to numbers, there is no difference between 0021 and 21. What you want is to either print out the reversed value directly as you're reversing it or build it as a string and then print it out.
The former approach would go like this:
System.out.print("The reversed number is ");
while (num != 0)
{
System.out.print(num % 10);
num = num / 10;
}
System.out.println();
The latter approach would go like this:
String reverse = "";
while (num != 0)
{
reverse = reverse + Integer.toString(reverse);
num = num / 10;
}
System.out.println("The reversed number is " + reverse);
The latter approach is useful if you need to do further work with the reversed value. However, it's suboptimal for reasons that go beyond the scope of this question. You can get more information if you do research about when it's better to use StringBuilder instead of string concatenation.
I actually found this way really interesting, as this is not how I usually would reverse it. Just thought to contribute another way you could reverse it, or in this case, reverse any String.
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
int num = n.nextInt();
System.out.println("The number before getting reversed is " + num);
String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = sNum.length()-1; i >= 0; i--)
{
sNumFinal += sNum.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
If you wanted to take this further, so that you can enter "00234" and have it output "43200" (because otherwise it would take off the leading zeros), you could do:
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
String num = n.next(); // Make it recieve a String instead of int--the only problem being that the user can enter characters and it will accept them.
System.out.println("The number before getting reversed is " + num);
//String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = num.length()-1; i >= 0; i--)
{
sNumFinal += num.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
And of course if you want it as an int, just do Integer.parseInt(sNumFinal);
The reason the two zero is being stripped out is because of the declaration of temp and reverse variable as integer.
If you assigned a value to an integer with zero at left side, example, 000001 or 002, it will be stripped out and will became as in my example as 1 or 2.
So, in your example 1200 becomes something like this 0021 but because of your declaration of variable which is integer, it only becomes 21.
import java.util.Scanner;
public class Reverse {
public static void main(String args[]){
int input,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
in.close();
}
}

Categories