Last word/sentence on an Array Java - java

I have an assignment, it looks pretty easy however I cannot figure it out how to solve it.
It says:
a) Ask the user: How many words/sentences do you want to write (at
least 5) ? (Use while loop)
b) Use for loop to make the user write the words/sentences
c) After the user's written the words/sentences, output which
word/sentence comes last alphabetically (using .compareTo() method )
This is what I came up with:
import java.util.Scanner;
import java.lang.String;
import java.util.Arrays;
public class LastString {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
final short MIN_NUM = 2;
int num = 0;
int count = 0;
String [] sentence = new String [0];
String last = "";
while (num < MIN_NUM){
System.out.println("How many words/sentences do you want to put? " + "\t\t\t\t\t\t\t\t --- at least " + MIN_NUM);
num = input.nextInt();
sentence = new String [num];
}
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
System.out.println("The word/sentence is: " + sentence[i]);
}
int i = 0;
int max;
for (i=0;i<num-1 ;i++ ) {
if(sentence[i].compareTo(sentence[i+1]) > 0){
last = sentence[i];
count ++;
}else if (sentence[i].compareTo(sentence[i+1]) < 0) {
last = sentence[i+1];
count++;
}
}
System.out.println("\n\n------------" +
"\nLast word/sentence is: " + last);
System.out.println(Arrays.toString(sentence));
}
}
I compiles and runs. I have two problems:
nextLine >>> it is skiping the first Sentence
I don't know how to make the algorithm to calculate which word/sentence has the biggest value or, using the compareTo() method which word/sentence has the value > 0 compared to each and every other value on the array.
Thank you.

Answer to Q1 : num = input.nextInt(); takes a number as the input but doesn't also consume the new-line, and hence the nextLine consumes the empty new line ... you could use input.nextLine also to get the first number instead of num = input.nextInt(); by reading a line, then parsing the int value as num = Integer.parseInt(input.nextLine());
Answer to Q2 :
You re-set the value of last everytime but you don't compare the value of the next biggest candidate with the last before re-assigning last ...
for example, look at the following :
for (int i = 0; i < num - 1; i++) {
String thisLast = "";
if (sentence[i].compareTo(sentence[i + 1]) > 0) {
thisLast = sentence[i];
count++;
} else if (sentence[i].compareTo(sentence[i + 1]) < 0) {
thisLast = sentence[i + 1];
count++;
}
if (thisLast.compareTo(last) > 0)
last = thisLast;
}

it will solve your problem....
int count = 0;
String [] sentence = new String[6];
String last = "";
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
count++;
if(count >= 2){
if(sentence[i].compareTo(last) > 0){
last = sentence [i] ;
}
}else{
last = sentence [i];
}
System.out.println("The word/sentence is: " + sentence[i]);
}

Related

how to remove the comma at the end [duplicate]

This question already has answers here:
Avoid printing the last comma
(13 answers)
Closed 1 year ago.
I'm writing a simple java code that takes two integers as min and max and a third integer as divisor and it finds all numbers between that are divisible by the third integer, which worked fine but in the output I can't get rid of the last comma.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int a = scanner.nextInt();
System.out.print("Enter the second number: ");
int b = scanner.nextInt();
System.out.print("Enter the divisor: ");
int d = scanner.nextInt();
for(int i=a; i<=b; i++) {
if(i%d == 0)
System.out.print(i+", ");
}
How could I do it?
I prefer to avoid the issue by writing commas before things where appropriate, and not after. It seems more straightforward to know when you're doing the first thing, compared to knowing when you're doing the last thing.
String sep = ""; // no separator before first print
for (int i=a; i<=b; i++) {
if (i%d == 0) {
System.out.print(sep + i);
sep = ", "; // separator for every following print
}
}
You can use an if statement to print a comma only if it is not the last element.
if(i%d == 0){
System.out.print(i);
if(((i/d)+1)*d <= b) System.out.print(", ");
}
For these kinds of problems the StringJoiner is especially useful:
StringJoiner out = new StringJoiner(",");
for(int i=a; i<=b; i++) {
if(i%d == 0)
out.add(Integer.toString(i));
}
System.out.println(out);
You can use as boolean to control printing the comma.
boolean addComma = false;
for (int i=a; i<=b; i++) {
if (i%d == 0) {
System.out.print((v ? "," : "") + i);
addComma = true;
}
}
You could use substringto strip the space and comma off the end if it is the last number. It is not as elegant as Unmitigated's solution, but it should work:
String validNumbers = "";
for(int i=a; i<=b; i++) {
if(i%d == 0)
validNumbers += i + ", ";
}
if (validNumbers != "") {
validNumbers = validNumbers.substring(0, validNumbers.length() - 2);
}
System.out.print(validNumbers);

String of only even numbers and only odd numbers

I know there are already questions asking something similar to my question, but despite reading those, they don't quite do what I want.
I am creating a code that takes a users input of a number between 0-100 (inclusive). Whatever the number, it will print all the numbers leading up to that number and that number
EX: user input = 25
output = 012345678910111213141516171819202122232425
I have that part working. Now I am supposed to use that string and create two new strings, one for only the odd and the other one for the even numbers.
EX: user input = 25
output: odd numbers: 135791113151719212325 & even numbers = 024681012141618202224
Here is my code so far:
import java.util.Scanner;
public class OddAndEven{
public String quantityToString() {
Scanner number = new Scanner(System.in);
int n = number.nextInt();
String allNums = "";
if ((n >= 0) && (n <= 100)) {
for (int i = 0;i <= n; ++i)
allNums = allNums + i;
return allNums;
}
else {
return "";
}
}
public void oddAndEvenNumbers(int num) {//Start of second method
String allNums = ""; //String that quantityToString returns
String odd = "";
String even = "";
if ((num >= 0) && (num < 10)) { //Looks at only single digit numbers
for (int i = 0; i <= allNums.length(); i++) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) { //trying to get the allNums string to be broken into individual numbers to evaluate
even = even + allNums.charAt(i); //adding the even numbers of the string
}
else {
odd = odd + allNums.charAt(i);
}
}
}
else { //supposed to handle numbers with double digits
for (int i = 10; i <= allNums.length(); i = i + 2) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) {
even = even + allNums.charAt(i);
}
else {
odd = odd + allNums.charAt(i);
}
}
}
System.out.println("Odd Numbers: " + odd);
System.out.println("Even Numbers: " + even);
}
public static void main(String[] args) {
System.out.println(new OddAndEven().quantityToString());
//System.out.println(new OddAndEven().oddAndEvenNumbers(allNums));
//Testing
OddAndEven obj = new OddAndEven();
System.out.println("Testing n = 5");
obj.oddAndEvenNumbers(5);
System.out.println("Testing n = 99");
obj.oddAndEvenNumbers(99);
I know my problem is at the part when its supposed to take the string apart and evaluate the individual numbers, but I don't know what to do. (I've also tried substring() & trim()) Also I have not learned how to use arrays yet, so that is why I did not try to use an array.
I think you can make it that way:
int x = 20;
StringBuilder evenNumberStringBuilder = new StringBuilder();
StringBuilder oddNumberStringBuilder = new StringBuilder();
for(int i =0 ; i<x+1; i++){
if(i % 2 == 0)evenNumberStringBuilder.append(i);
else oddNumberStringBuilder.append(i);
}
System.out.println(evenNumberStringBuilder);
System.out.println(oddNumberStringBuilder);
Output:
02468101214161820
135791113151719
you are already taking the input as integer, so don't work with strings. I recommend that to use this loop;
Scanner number = new Scanner(System.in);
System.out.print("Even Numbers: ");
for (int i = 0; i <= number; i=i+2) {
System.out.print(i);
}
System.out.println("");
System.out.print("Odd Numbers: ");
for (int i = 1; i <= number; i=i+2) {
System.out.print(i);
}
You can simply evaluate numbers while storing them in an allnumbers string, here's a functioning code:
int x = 23; //user input
String s=""; //contains all numbers from 0 to userinput
String odd =""; //contains all odd numbers from 0 to userinput
String even = ""; //contains all even numbers from 0 to userinput
for(int i = 0 ; i< x+1 ; i++){
s += i;
if(i%2==0) //if i is an even number
even += i;
else //if i is an odd number
odd += i;
}
System.out.println(s); //displaying all numbers from 0 to user input
System.out.println(odd); //displaying odd numbers from 0 to user input
System.out.println(even); //displaying even numbers from 0 to user input

Program about how many times the number has been repeated

For example i want to find how many times 1 repeated in number 123900148
It must be write 2 times but i get wrong values for everytime
Scanner input = new Scanner(System.in);
#author Başar Ballıöz
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
for (int i = 0; i < number.length() - 1 ; i++) {
if (number.substring(i , i+1).equals(repeat))
counter++;
}
System.out.println(repeat + " number " + counter + " repeated.");
i would like to see my output like:
number : 134211
number i want to find how many times repeated: 1
your number has repeated 3 times
You are comparing a String (returned by number.substring(i , i+1) to an Integer, so of course it will always return false.
Either compare two ints or two Strings. Since you are essentially comparing two digits, comparing ints would be more efficient.
for (int i = 0; i < number.length(); i++) {
if (Character.getNumericValue(number.charAt(i)) == repeat) {
counter++;
}
}
Scanner input = new Scanner(System.in);
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
while (tmp > 0) {
if (tmp % 10 == repeat) {
counter++;
}
tmp = tmp/10;
}
System.out.println(number + " number " + counter + " repeated.");
You're comparing a String against an Integer via equals hence you're not getting the expected result. instead convert the integer to a string prior to comparison:
if (number.substring(i , i+1).equals(String.valueOf(repeat)))
Further, you could cache the result of String.valueOf(repeat) into a variable before the for loop to prevent a string object construction in each iteration of the loop.
Try this. I added some helpful output so you can see how it's indexed.
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
public class CountChars {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter A String: ");
Map<String, Integer> map = indexString(input.nextLine());
while (true) {
System.out.print("Enter A Character You Want To Count (ENTER to exit): ");
String repeat = input.nextLine();
if (repeat == null || repeat.isEmpty()) {
break;
}
System.out.println(String.format("'%s' was repeated %d time(s).", repeat, (map.containsKey(repeat)) ? map.get(repeat):Integer.valueOf(0)));
}
}
private static Map<String, Integer> indexString(String s) {
Map<String, Integer> map = new HashMap<>();
System.out.println(String.format("'%s' has %d characters. Indexing now.", s, s.length()));
for (int i = 0; i < s.length() ; i++) {
String c = String.valueOf(s.charAt(i));
if (!map.containsKey(c)) {
map.put(c, 0);
System.out.println(String.format("Indexing %s", c));
}
System.out.print(String.format("Incrementing '%s' from %d ", c, map.get(c)));
map.put(c, map.get(c) + 1);
System.out.println(String.format("to %d.", map.get(c)));
}
return map;
}
}

Java program keeps exiting program prematurely

I need to build a simple automaton for my Automata class. I am using Java and I cannot figure out for the life of me why my program keeps exiting prematurely. I've tried debugging it, having print statements everywhere to figure out where it's stopping, and although I know where it stops, I do not see anything that would make the program stop working. The stoppage happens on line 27 (Right where I SOP "Enter a string of digits...".
Knowing me it's probably something simple, but I cannot figure this one out.
import java.util.*;
public class hw1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please indicate the number of states");
int numState = input.nextInt();
int[] state = new int[numState];
boolean[] accept = new boolean[numState];
for (int i = 0; i < numState; i++) {
System.out.println("Is the state q" + (i + 1) + " a final state? (Answer 1 for yes; 0 for no)");
int finalState = input.nextInt();
if (finalState == 1)
accept[i] = true;
} // for
System.out.println("Enter the number of symbols s: ");
int numSym = input.nextInt();
int[][] next = new int[numState][numSym];
for (int i = 0; i < numState; i++) {
for (int j = 0; j < numSym; j++) {
System.out.println("What is the number for the next state for q" + i + " when it gets symbol " + j);
next[i][j] = input.nextInt();
}//nested for
}//for
String digits = input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
int[] digitArray = new int[digits.length()];
for (int i = 0; i < digits.length(); i++) {
digitArray[i] = digits.charAt(i);
}
for (int i = 0; i < digits.length(); i++) {
System.out.print(digitArray[i] + " ,");
}
System.out.println("end of program");
}// main;
}// class
Change your code to :
input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
String digits = input.nextLine();
This will get and ignore the newline character left in the stream after call to nextInt()

How to use an array in for loop to calculate minimum?

I am trying to use an array, but I am not sure if that is the right way to do this.
I want the first and second integer input to compare with one another, then if there are more they compare with each other.
So here is the piece of the code.
for(int ii = 1, j = 0; j <= copySel ; ii++, j++) {
int x = 0;
int[x] check;
// Prompt as follows
System.out.print("Enter value " + ii + ": ");
try {
c = Get();
}
catch (InputMismatchException e) {
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
ii--; x--;
} check = c; x++;
System.out.print(check + " "+ x);
}
My actual format is not this bad. I need to try to find the minimum value depending on the number of integer the user has input
static int Get()
{
Scanner intFind = new Scanner(System.in);
int select;
select = intFind.nextInt();
return select;
}
This is Get() ^
cant I use min(x, y) continuously?
int min=a[0];
for(int i=1;i<n;i++)
{
if(a[i] < min)
min = a[i];
}
System.out.println("The min is "+min);
System.out.print("Enter value " + ii + ": ");
int min = Get();
int c = 0;
for(int ii = 1, j = 0; j < copySel ; ii++, j++) {
// Prompt as follows
System.out.print("Enter value " + ii + ": ");
try {
c = Get();
}
catch (InputMismatchException e) {
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
ii--;
} min = Math.min(min, c);
System.out.print("minimum is:"+ min);
}
if you have a integer array you could do as below
Integer [] arr = {5,2,3,4,5,6,7,8};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(arr));
Collections.sort(list);
System.out.println("Minimum "+list.get(0)); ;
Scanner in = new Scanner(System.in);
System.out.println("Enter the integers: ");
String s = in.nextLine();
string[] str = s.plit(" ");
int[] a = new a[str.length];
for(int i =0; i< str.length; i++)
{
a[i] = Integer.parseInt(str[i]);
}
//Madar's code
int min=a[0];
for(int i=0;i<a.length;i++)
{
min = Math.min(a[i], min);
}
System.out.println("The min is "+min);
I didn't get what your trying to do exactly, but here's some errors you might consider to repair. If check is an array you have to initialize it as such:
int[] check;
Does get() give you back an array of integer, if so you cannot make check = c, you have to copy or clone the content of c into check as such:
check = (int[])c.clone();

Categories

Resources