I was asked to create a JOptionPane program which takes as many numbers as the user wants (as a string) and sums them together.
I thought about a pseudo like this:
make int Total = 0
receive input as string X
loop: for (int i = 0; i<=X.length();i++)
create another string S1 which takes the number from the beginning until the first space
convert S1 into a number and add it to Total
subtract S1 from X, and start the loop over
show total
So, my problem is at subtracting the S1 from the X.
My code so far:
public static void main(String[] args) {
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
for (int i = 0; i<=x.length();i++){
String s1 = x.substring (0, x.indexOf(' '));
total += Integer.parseInt(s1);
x = x - s1;
}
JOptionPane.showMessageDialog(null, "the sum is" + total); }
If you didn't learn arrays yet, you can implement this like that :
public static void main(String[] args){
int total = 0;
String x = "12 7";
String s1 = x.trim(); //trim the string
while(!s1.isEmpty()){ //loop until s1 is not empty
int index = x.indexOf(' ');//search the index for a whitespace
if(index != -1){ //we found a whitespace in the String !
s1 = s1.substring(0, index); //substract the right number
total += Integer.parseInt(s1);
x = x.substring(index+1).trim(); //update the String x by erasing the number we just added to total
s1 = x; //update s1
} else {
total += Integer.parseInt(s1); //when there is only one integer left in the String
break; //break the loop this is over
}
}
System.out.println(total);
}
This is another interpretation of the method #ZouZou used, but doesn't actually break up your string, it remembers where its already looked, and works its way along the string
int total = 0;
String inputString = "12 7 8 9 52";
int prevIndex = 0;
int index = 0;
while (index > -1) {
index = inputString.indexOf(' ', prevIndex);
if (index > -1) {
total += Integer.parseInt(inputString.substring(prevIndex, index));
prevIndex = index + 1;
} else {
total += Integer.parseInt(inputString.substring(inputString.lastIndexOf(' ')+1));
break;
}
}
System.out.println(total);
Simple solution
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
for (String s : x.split("\\s+")){
total += Integer.parseInt(s);
}
System.out.println(total);
Edit: "can't use arrays"- then use a Scanner to scan the String for nextInt()
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
Scanner scanner = new Scanner(x); // use scanner to scan the line for nextInt()
while (scanner.hasNext()){
total += scanner.nextInt();
}
System.out.println(total);
Related
Write a program where the user types in a number of Strings which are stored in an array of Strings and then the program prints out all the longest Strings entered by the user.
HAVE A PROBLEM HOW TO PRINT ALL SAME LONGEST LENGTH() According to this sentence that required "the program prints out all the longest Strings"
PS. My code can only print out ONE longest length string NOT ALL longest String. How to fixed it.
public static void method4(){
Scanner console = new Scanner(System.in);
String[] list = new String[5];
int maxLength = 0;
String longestString = null;
String longestString1 = null;
for (int i = 0; i < list.length; i++) {
System.out.println("Enter a string 5 times: ");
list[i] = console.next();
if (list[i].length() > maxLength){
maxLength = list[i].length();
longestString = list[i];
}
}
System.out.println("Longest string: "+longestString+ "\n\t\t"+longestString1);
}
The problem with your code is: inside the loop that you are getting the user's input, you print the "longest string" at that moment.
This means that the 1st string that the user enters will be a "longest string" and will be printed because its length is compared to 0 and of course it is longer.
You must separate the input of the strings and the output (printing of the longest strings) in 2 separate loops. The 1st loop gets the strings and by comparing calculates the length of the longest string and the 2nd iterates through all the string and prints it only if its length is equal to the maximum length that was calculated in the 1st loop:
String[] list = new String[5];
int maxLength = 0;
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < list.length; i++) {
System.out.println("(" + (i + 1) + ") Enter a string: ");
list[i] = scanner.nextLine();
if (list[i].length() > maxLength){
maxLength = list[i].length();
}
}
scanner.close();
int counter = 0;
for (String s : list) {
if (s.length() == maxLength){
counter++;
System.out.println("(" + counter + ") Longest string: " + s + "\n");
}
}
You have to do it in two pass. First loop finds the max length of string. Then second loop can iterate and print only strings that have max length,
public static void method4(Scanner console){
String[] list = new String[5];
int maxLength = 0;
System.out.println("Enter a string 5 times: ");
for (int i = 0; i < list.length; i++) {
list[i] = console.next();
if (list[i].length() > maxLength){
maxLength = list[i].length();
}
}
for (int i = 0; i < list.length; i++) {
if (list[i].length() == maxLength) {
System.out.println("Longest string: "+list[i]);
}
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
method4(sc);
sc.close();
}
There are other approaches too where you can store the longest strings in a set as you encounter them and reset the set the moment you find a new longer string and finally print all the strings in the Set.
I would like to split this input: 12132002(177) 012(207.5) 014(184) into two arrays, like this:
num[500] = 12132002,012,014, etc.
and
mark[500] = 177,207.5,184, etc.
The Fact is that I'm accepting values from user like this, where i don't know the total number which he/she will input.
How can I code in Java that kind of splitting? Is it like this?
int number[500];
for(int i=0;i<500;i++) {
number=num.split("//(");
}
To code "that kind of splitting", you will have to:
Declare your variables: String[] number, String[] mark, String num, and String[] numSplit.
Split num by " " (spaces). Assign this to numSplit.
Loop through numSplit from 0 to numSplit.length with i.
Set number[i] to numSplit[i] from the beginning to the first occurrence of a "(".
Set mark[i] to numSplit[i] from one character after the first occurrence of "(" to one character before the end.
Output number and mark
The full code:
String[] number = new String[500]; //1
String[] mark = new String[500];
String num = "12132002(177) 012(207.5) 014(184)";
String[] numSplit = num.split(" "); //2
for(int i = 0; i < numSplit.length; i++) { //3
number[i] = numSplit[i].substring(0, numSplit[i].indexOf("(")); //4
mark[i] = numSplit[i].substring(numSplit[i].indexOf("(") + 1, numSplit[i].length() - 1); //5
}
for(int i = 0; i < number.length; i++) System.out.println(number[i]); //6
for(int i = 0; i < mark.length; i++) System.out.println(mark[i]);
Which outputs:
12132002
012
014
null (x497)
177
207.5
184
null (x497)
Notice that number, mark, and numSplit are String arrays because the leading zeros would be cut off in not otherwise. If you don't mind the leading zeros being cut off then you can change num to an int array and mark to a double array (Because of the decimal in 207.5).
Ok buddy, this could be a solution for your problem. I chose to use the methods I have already created for some other project, but I think those can fit for this purpose as well, instead of using some complex REGEX expression. The output is good, though you have to figure out the way you want to store num and mark variables (I suggest arrays). Hope I helped.
public class Example {
public static void main(String[] args) {
String s = "12132002(177)012(207.5)014(184)";
// output 12132002,012,014 && 177,207.5,184
// it works good with this string as well -> s = "12132002(177)012(207.5)014(184)111(024)";
int numOfParanthesis = numOfParanthesis(s, '(');
String num = "";
String mark = "";
// array which contains positions of (
int[] indexesOpening = indexes(s, '(');
// array which contains positions of )
int[] indexesClosing = indexes(s, ')');
// logic
for(int i = 0; i < numOfParanthesis; i++){
if(i == 0){
num = s.substring(i, indexesOpening[i])+",";
mark = s.substring(indexesOpening[i]+1,indexesClosing[i])+",";
}else if(i!=numOfParanthesis-1){
num += s.substring(indexesClosing[i-1]+1, indexesOpening[i])+",";
mark += s.substring(indexesOpening[i]+1, indexesClosing[i])+",";
}else{
num += s.substring(indexesClosing[i-1]+1, indexesOpening[i]);
mark += s.substring(indexesOpening[i]+1, indexesClosing[i]);
}
}
System.out.println(num);
System.out.println(mark);
}
// returns array of positions for the given character
public static int[] indexes(String s, char c){
int numOfParanthesis = numOfParanthesis(s, c);
int[] indexes = new int[numOfParanthesis];
int delimetar = s.indexOf(c);
for(int i = 0; i < numOfParanthesis; i++){
if(i != -1){
indexes[i] = delimetar;
}
delimetar = s.indexOf(c, delimetar+1);
}
return indexes;
}
// returns how many times a character repeats in a string
public static int numOfParanthesis(String s, char c){
int number = s.indexOf(c);
int i = 0;
while (number >= 0){
number = s.indexOf(c, number+1);
i++;
}
return i;
}
}
Try this:
public class Test {
public static void main(String[] args) {
// Guess this is a string since it is a mix of integers
// and non-integers, characters like '(', ')' and space.
String str = "12132002(177) 012(207.5) 014(184)";
System.out.println("Your string:");
System.out.println("str=\"" + str + "\"");
System.out.println();
// remove all ')' since they will not be used
// using space as a delimiter is enough
String str2 = str.replaceAll("\\)", "");
System.out.println("Your string after removing ')' character:");
System.out.println("str2=\"" + str2 + "\"");
System.out.println();
// Since your input has spaces, we split on spaces
String[] strings = str2.split("\\s+");
System.out.println("Result after splitting str2 by spaces:");
for (String s : strings) {
System.out.println(s);
}
System.out.println();
// Lets make two array
String[] num = new String[500];
String[] mark= new String[500];
// loop strings
int cnt = 0;
for (String s : strings) {
String[] a = s.split("\\("); // a[0]="012", a[1]="207.5"
num[cnt] = a[0];
mark[cnt] = a[1];
cnt++;
}
System.out.println("Result num: ");
System.out.print("num[500] = ");
for(String s : num) {
if(s==null) {break;}
System.out.print(s + ",");
}
System.out.println(" etc.\n");
System.out.println("Result mark: ");
System.out.print("mark[500] = ");
for(String s : mark) {
if(s==null) {break;}
System.out.print(s + ",");
}
System.out.println(" etc.\n");
}
}
Output:
Your string:
str="12132002(177) 012(207.5) 014(184)"
Your string after removing ')' character:
str2="12132002(177 012(207.5 014(184"
Result after splitting str2 by spaces:
12132002(177
012(207.5
014(184
Result num:
num[500] = 12132002,012,014, etc.
Result mark:
mark[500] = 177,207.5,184, etc.
OK thanks so now the code can find the word in the string array but now I need to get the most positive word from the user input and the most negative word from the user input. So if I plug in dreadful zone, dreadful is 1.25 and zone is 2.66, so dreadful is the most negative word and zone is the most positive word but how the code is set up I don't know how to keep track of those values then make sure that it can print out the correct word as the most positive and the word as the post negative. So the average of the user input is printed. I tried doing parallel arrays but I want to avoid those. The other issues are being able to take multiple inputs from the user until they use the keys ctrl z or ctrl d. (I was told they are part of Eclipse but I have no idea how to use them.)
Thank you for any suggestions on how to proceed.
Output:
Please type one line of review and when you are done press either Ctr D or Ctr Z
dreadful zone
dreadful zone
The average is negative at 1.9583333333333333
Incomplete assignment
public class MovieReviewSentimentAnalysis {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// TODO: complete me
//make own arrays to pass by value
//movieReviewComments = the text
String[] movieReviewComments = new String[8529];
//movieReviewScores = numeric values, avoid lit. values
int[] movieReviewScores = new int[8529];
String userComment = "";
MovieReviewReader.readMovieReviews("movie_reviews.txt", movieReviewComments, movieReviewScores); //string, string array, and int array
System.out.println("Please type one line of review and when you are done press either Ctr D or Ctr Z");
userComment = userInput.nextLine();
System.out.println(userComment);
// String[] words = userComment.split("\\s+");
String[] words2 = userComment.split("[\\W]"); //splits at "\W", or non-word characters
double singularUserWordTotal = 0;
double wordTotal = 0;
double totalSumOfUserCommentWords = 0;
double highestWordScore = 20;
double lowestWordScoreTotal = 0;
int locationOfWordInUserInput = 0;
String userInputWord = "";
// int itemCount = words.length;
for (int i = 0; i < words2.length; i++)
{
userInputWord = words2[i];
singularUserWordTotal = wordCount(userInputWord, movieReviewComments, movieReviewScores);
wordTotal += singularUserWordTotal;
totalSumOfUserCommentWords = wordTotal / words2.length;
// locationOfWordInUserInput = i;
// if(singularUserWordTotal > highestWordScore)
// {
// singularUserWordTotal = highestWordScore;
// }
// if(singularUserWordTotal < highestWordScore)
// {
// singularUserWordTotal = highestWordScore;
// lowestWordScoreTotal = singularUserWordTotal;
// }
}
displayScores(totalSumOfUserCommentWords);
// System.out.println(reviewFile);
System.out.println("Incomplete assignment");
userInput.close();
}
public static double wordCount(String userInputWord, String[] movieReviewComments, int[] movieReviewScores)
{
double storeScore = 0;
double totalSumOfReviewScores = 0;
double numOfTimesWordAppears = 0;
for (int i=0; i < (movieReviewComments.length); i++)
{
if (movieReviewComments[i].contains(userInputWord))
//PUNCTUATION IS A PROBLEM (if it's at the end of the user input then it's fine though)
{
storeScore = movieReviewScores[i];
totalSumOfReviewScores += storeScore;
numOfTimesWordAppears++;
//System.out.println("Found");
//What if the word doesn't appear in the text file?????
}else if (!movieReviewComments[i].contains(userInputWord))
{
numOfTimesWordAppears += 0;
}
// else
// System.out.println("You dun goofed"); //delete after fixing problem
}
double wordScoreAverage = totalSumOfReviewScores / numOfTimesWordAppears;
return wordScoreAverage;
}
public static double displayScores(double userCommentTotal)
{
if(userCommentTotal > 2.01)
{
System.out.println("The average is positive at " + userCommentTotal);
}else if(userCommentTotal < 2.01 && userCommentTotal > 1.99)
{
System.out.println("The average is neutral at " + userCommentTotal);
}else
System.out.println("The average is negative at " + userCommentTotal);
return userCommentTotal;
}
You can try to use HashMap for this:
Map<String,Integer> h = new HashMap<String,Integer>();
h.put(word,word_score);
//get word score
int score = h.get(word)
I'm trying to convert from integer to string to read in a sequence of digits in a string. The input needs to be one string each time, not one integer. the number that will be stored in an arraylist should not be integer but a string.
//wbin
//ow
int count = 0;
int total = 0;
final int SENTINEL = 0;
int score;
`
int sum;
Scanner scan = new Scanner(System in);
ArrayList list = new Array();
System.out.println("Enter your digits");
System.out.println("Enter 0 to calculate");
score = scan.nextint();
while ( score !=SENTINEL)
{ total = score + total;
list.add(score);
count++;
System.out.println("next number");
score = scan.nextint();
}
if (count != 0)
{
DecimalFormat oneDecimalPlace = new DecimalFormat( "##.0" );
System.out.println("\nYour Average is "
+ oneDecimalPlace.format( (double) ( total / count) ) );
System.out.println("Your Total is " + total);
for (int i = list.size()-1; i >= 0; i--)
System.out.println(list.get(i));
}
else
System.out.println( "\nNo digits were entered" );
ArrayList list = new Array();
why don't you use an ArrayList of Strings?
ArrayList<String> list = new ArrayList<>();
-
score = scan.nextint();
why don't you ask for the next line instead of the next int?
score = scan.nextLine();
That would solve your question, but, if you are doing arithmetic operations to those numbers why would you want to store them as Strings in the first place? you will end up concatenating Strings when you are supposed to add up the score to the total.
String s = Integer.toString(n); or String s = "" + n;
this code will give you integer to string conversion.
List item
I created a Palindrome program in Java that takes a word or words entered by the user and puts them into an array. It then takes the reversed input and puts it into another array. I then check to see if the two words are the same.
My problem is that the program is changing one of the letters so that it is always true and it's iterating too many times. Any ideas as to what in my code is causing this?
public static boolean isPalindrome(char[] a, int used){
char[] original = a;
int newNumber = used - 1;
for(int i = 0; i <= newNumber; i++){
a[i] = a[newNumber - i ];
System.out.println("Your original word was: " + String.valueOf(original));
System.out.println("Backwards, your word is: " + String.valueOf(a));
}
if(String.valueOf(original).equalsIgnoreCase(String.valueOf(a))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
return(String.valueOf(original).equalsIgnoreCase(String.valueOf(a)));
}
public void userInput(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a word or words that you believe are palindromes: ");
word = keyboard.next();
word = word.replaceAll("\\W","");
int length = word.length();
char[] p = new char[length];
for(int i = 0; i < length; i++){
p[i] = word.charAt(i);
}
Palindrome.isPalindrome(p, length);
}
This is my output when I type in "Candy."
Your original word was: yandy
Backwards, your word is: yandy
Your original word was: ydndy
Backwards, your word is: ydndy
Your original word was: ydndy
Backwards, your word is: ydndy
Your original word was: ydndy
Backwards, your word is: ydndy
Your original word was: ydndy
Backwards, your word is: ydndy
Your word or words are palindromes
Thanks to everyone that answered!
Here is the correct code that works, although not as efficient as it could be:
public static boolean isPalindrome(char[] a, int used){
char[] original = a;
char[] newArray = new char[used];
int newNumber = used - 1;
for(int i = 0; i <= newNumber; i++){
newArray[i] = a[newNumber - i ];
}
System.out.println("Your original word was: " + String.valueOf(original));
System.out.println("Backwards, your word is: " + String.valueOf(newArray));
if(String.valueOf(original).equalsIgnoreCase(String.valueOf(newArray))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
return(String.valueOf(original).equalsIgnoreCase(String.valueOf(newArray)));
}
In your Palindrome function:-
for(int i = 0; i <= newNumber; i++){
a[i] = a[newNumber - i ];
System.out.println("Your original word was: " + String.valueOf(original));
System.out.println("Backwards, your word is: " + String.valueOf(a));
}
here you are replacing the existing array.
You can even try the following code:-
String original, reverse="";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
Problem is with your code a[i] = a[newNumber - i ]; you are changing the existing array.
First create new array and then put your reverse string in that.
public static boolean isPalindrome(char[] a, int used) {
char[] newA = new char[a.length];
int newNumber = used - 1;
for (int i = 0; i <= newNumber; i++) {
newA[i] = a[newNumber - i];
System.out.println("Your original word was: " + String.valueOf(a));
System.out.println("Backwards, your word is: " + String.valueOf(newA));
}
if (String.valueOf(String.valueOf(newA)).equalsIgnoreCase(String.valueOf(a))) {
System.out.println("Your word or words are palindromes.");
} else {
System.out.println("Your word or words are not palindromes");
}
return (String.valueOf(String.valueOf(newA)).equalsIgnoreCase(String.valueOf(a)));
}
There are many other efficient ways to write this code.
If you want to check palindrome in this easy way, you can try with StringBuilder.
public static boolean isPalindrome(String input) {
StringBuilder sb=new StringBuilder(input);
return input.equals(sb.reverse().toString());
}
In your case change your isPalindrome method as follows
public static void isPalindrome(char[] a, int used){
char[] newArr = new char[a.length]; // create a new array in same length as a
int newNumber = used - 1;
System.out.println("Your original word was: " + String.valueOf(a));
for(int i = 0; i <= newNumber; i++){
newArr[i] = a[newNumber - i ];
}
System.out.println("Backwards, your word is: " + String.valueOf(newArr));
if(String.valueOf(newArr).equalsIgnoreCase(String.valueOf(a))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
}
there is no need to copy the array (you only copied the referenz), only creat a new array with the same size and use a as the original array.
char[] reverse = new char[used];
put the system.out, out of the for loop:
for(int i = 0; i <= newNumber; i++){
reverse[i] = a[newNumber - i ];
}
System.out.println("Your original word was: " + String.valueOf(a));
System.out.println("Backwards, your word is: " + String.valueOf(reverse));
the whole isPalindrom function:
public static boolean isPalindrome(char[] a, int used){
char[] reverse = new char[used];
int newNumber = used -1;
for(int i = 0; i <= newNumber; i++){
reverse[i] = a[newNumber - i ];
}
System.out.println("Your original word was: " + String.valueOf(a));
System.out.println("Backwards, your word is: " + String.valueOf(reverse));
if(String.valueOf(reverse).equalsIgnoreCase(String.valueOf(a))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
return(String.valueOf(reverse).equalsIgnoreCase(String.valueOf(a)));
}
The problem is in isPalindrome method where you assigned
char[] original = a;
The char[] variables are references. By setting original = a, you're copying the reference, so now both the arrays are pointing to the same chunk of memory.
Now, when you modify a, original also gets modified because both are pointing to same memory.
You can fix this by creating a new instance as shown below:
char[] original = new char [a.length];
System.arraycopy( a, 0, original, 0, a.length );