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.
Related
I'm having some problems splitting a string that is read in from an input file, making sure it's valid, then saving it to a variable.
Let's say this is the first string:
12345 5 59.28
I would want to split the 12345, 5, and 59.28.
After verifying that they are the correct format ( 00000-99999, 0-5, 000.00 0 100.00 ), I would then assign it to a variable.
My main two obstacles are that I CANNOT use arrays in this program, so I'm not sure how to split the string. I have tried just pulling each section as an int, but that doesn't seem to work.
My other problem is that I'm not sure how to validate it. Would I be using something like this:
//Assuming I have a scanner set up and a class, method declared
//Declare variables
int numbers;
int studentID;
while(fileInput.hasNext())
{
numbers = fileInput.nextInt(); //Not sure how to pull a part of the string
}
//Used to validate that it is within the range
if(numbers < 00000 || numbers > 99999)
{
studentID = numbers;
}
I am a beginner at Java so please do excuse my confusion.
If you know what the structure of the file is, for example if it's always formatted like this:
int int double
Then you can simply callnextInt(), nextInt(), and then nextDouble() to parse the data from it that way.
Maybe something like this
do
{
num1 = scanner.nextInt();
num2 = scanner.nextInt();
num3 = scanner.nextDouble();
} while (scanner.hasNextInt());
And do that in order to collect all of your data, but you'll likely need lots of variables if you have any substantial amount of data you're reading in
Or if there's bad data sometimes with it's correct data immediately after it you could so something like this to skip over the bad one, even though it's not very pretty
do
{
if (scanner.hasNextInt())
{
num1 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num1 = scanner.nextInt();
}
if (scanner.hasNextInt())
{
num2 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num2 = scanner.nextInt();
}
if (scanner.hasNextDouble())
{
num3 = scanner.nextDouble();
}
else
{
scanner.next() // move past whatever bad data there was
num3 = scanner.nextDouble();
}
} while (scanner.hasNext());
I think your teachers give this assignment to practice your if-else condition or switch statement and for loop(fundamental) skills.
Here what I did, this may be not completely match with your assignment question but using this you can get complete idea and think of a way to reduce this. Hey! because of we are not here to do your assignment. you have to tackle with your problem and get familiar with those.
Try to understand these, do changes look what happen:
public static void main(String[] args) {
Scanner fileInput = new Scanner(System.in);
//Declare variables
String numbers = "";
String firstNum = "";
String secondNum = "";
String thirdNum = "";
int studentID = 0;
int secondDigit = 0;
double thirdDigit = 0;
System.out.print("Input: ");
numbers = fileInput.nextLine();
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
firstIndex = numbers.indexOf(" ");
if(firstIndex <= 4){
System.out.println("Number should be 5");
}else{
firstNum = numbers.substring(0, firstIndex);
numbers = numbers.substring(firstIndex+1);
studentID = Integer.parseInt(firstNum);
if(studentID > 0 && studentID < 99999){
System.out.println("First num: " +firstNum);
}else{
System.out.println("first digits not in a range ");
}
}
secondIndex = numbers.indexOf(" ");
if(secondIndex == 0){
System.out.println("no number");
}else{
secondNum = numbers.substring(0, secondIndex);
numbers = numbers.substring(secondIndex+1);
secondDigit = Integer.parseInt(secondNum);
if(secondDigit >= 0 && secondDigit <= 5){
System.out.println("Second num: " +secondNum);
}else{
System.out.println("second digit not in a range ");
}
}
thirdIndex = numbers.length();
if(thirdIndex < 3){
System.out.println("3 numbers should be there");
}else{
thirdNum = numbers.substring(0, thirdIndex);
thirdDigit = Double.parseDouble(thirdNum);
if(thirdDigit >= 0 && thirdDigit <= 100){
System.out.println("third num: " +thirdNum);
}else{
System.out.println("third digit not in a range ");
}
}
}
I'm not going to explain this also. You have to try, if you have any problem after tackling with this code. ask any question in comment.
Hope this will help!
Try this. Invalid formats will throw an exception during the next method call.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner("12345 5 59.28");
in.useDelimiter(" "); // reads per space
String next = in.next("\\d{5}"); // reads next 5 digits
int numbers = Integer.valueOf(next);
System.out.println(numbers);
next = in.next("\\d{1}"); // reads next 1 digit
int studentId = Integer.valueOf(next);
System.out.println(studentId);
next = in.next("\\d{2}\\.\\d{2}"); // reads next a decimal with two digits before and after point
float floatingNumbers = Float.valueOf(next);
System.out.println(floatingNumbers);
}
}
<script src="//repl.it/embed/IWzC/0.js"></script>
I am trying to create a "calculator", except it needs to print each element that was used to compose the sum total. This printing of the array elements needs to happen at the end of the program, when the user inputs 0 twice in a row.
Upon entering an input, the integer values will be stored in an array. Once the end of the program has been reached, the contents of this array will be printed. However, if the end of the program has not been reached, the program continues while the user adds consecutive inputs.
Currently, the program will only print one element at a time, instead of every element that was used to calculate the total. I've spent hours trying to debug, and any guidance would be greatly appreciated!
import java.util.*;
public class AddingMachine {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean justStarting = true;
int total = 0;
int subtotal = 0;
int input;
int last = 1;
int MAXIMUM_NUMBER_OF_INPUTS = 100;
while (true) {
input = scanner.nextInt();
if (input == 0) {
if (last == 0) {
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
subtotal += input;
last = input;
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; i++) {
numbers[i] = last;
}
System.out.println(Arrays.toString(numbers));
}
}
When summing the input in your loop, you could store the users input into a List of integers. Once you need to reprint them, you can iterate over the List and print the elements you stored.
Example:
List<Integer> storedUserInput = new ArrayList<>();
while (true) {
input = scanner.nextInt();
storedUserInput.add(input);
if (input == 0) {
if (last == 0) {
for(Integer i : storedUserInput){
System.out.print(i + " + ");
}
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
}
Within the while loop, the array is re-initialized each time:
int[] numbers = new int[args.length];
so any previously entered value is lost. Also, the purpose of the for loop within the while is not clear.
Also, unless using an array is a requirement, you really don't need an array. You could just use a StringBuffer and append the entered values.
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 have created a program that uses the Scanner to ask the user for int values until they insert -1 which makes the program to stop receiving numbers. After doing so, it will add all the values entered by the user. This is my code so far:
public static void main(String[] args)
{
int sum = 0, value, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (-1 to quit): ");
value = scan.nextInt();
String string = Integer.toString(value);
while (value != -1)
{
count = count + 1;
sum = sum + value;
System.out.print("Enter an integer (-1 to quit): ");
value = scan.nextInt();
string = Integer.toString(value);
}
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
System.out.println("Number entered: " + string + ",");
System.out.println ("The sum is " + sum);
}
}
I want the output to look like this:
Entered numbers: 1,2,3,4,5 //example of number the user might enter
The sum is 15
I wanted to use a String for it to give me the sets of entered numbers, but it only gives me the last entered value. Which is -1 because that is the number that has to be entered to stop the program.
How can I out this problem?
In your
while(value != -1){
...
string = Integer.toString(value);
}
you are replacing string value with new one, so old value is lost. You should add new value to previously stored one. So your code may look like
string = string + "," + value;
You should also place this code before handling value which will be -1.
BTW, when you will learn more about Java you will know that each time you call
string + "," + value
new String is being created. Such string will need to copy content of other chunks. which may be very inefficient in case of long strings. To optimize this we can use StringBuilder and append new parts to it in loop.
In Java 8 we can also use StringJoiner which can automatically add prefixes, delimiters and suffixes for us.
Simply use string += "," + Integer.toString(value); This will give you a comma separated list of all the values you have entered. Your current statement string = Integer.toString(value); causes the variable string to be reset to the string representation of "value" for every iteration.
Check this code.
public static void main(String[] args)
{
int sum = 0, value, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (-1 to quit): ");
value = scan.nextInt();
StringBuilder sb = new StringBuilder();
while (value != -1)
{
if(sb.length() == 0){
sb.append(value);
}else{
sb.append(","+value);
}
count = count + 1;
sum = sum + value;
System.out.print("Enter an integer (-1 to quit): ");
value = scan.nextInt();
}
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
System.out.println("Number entered: " + sb.toString());
System.out.println ("The sum is " + sum);
}
}
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);