Initialize Variables in a loop - java

What I'm trying to do is have a loop to get a users input, convert it to an integer, create a variable and store the integer to that new variable. If the user doesn't input the word "end" it will continue to do this until the user does so. The thing I'm having trouble with is creating the variables. I'd like to just have them a, b, c, d, e, and so on. The rest of the program I can do, just need pointed in the right direction for this.

If you don't know how many values you're going to get, you really need to store them in a Collection such as a List.
What are you going to do with the values once they are all input?

I would use a array for this and it sounds like you need two variables:
String sInput;
int iInput[];
Then in your loop you can test to see if sInput is a number and not "end" after which you can parse it to your array:
iInput[index] = Integer.parseInt(sInput);
later you can then access each element in the array iInput[0], iInput[1]...
Be aware you must define the array size and when you do in Java you can not change it or make it bigger.
I hope this gets you going.

If you are in a loop, odds are you don't need a new variable for every iteration in the loop, so instead of having a solution like
int input1;
int input2;
int input3;
int input4;
int input5;
for (int index = 0; index < 5; index++) {
if (index == 0) {
input1 = getInput();
}
if (index == 1) {
input2 = getInput();
}
if (index == 2) {
input3 = getInput();
}
if (index == 3) {
input4 = getInput();
}
if (index == 4) {
input5 = getInput();
}
}
you can probably live with a solution like
int input;
for (int index = 0; index < 5; index++) {
input = getInput();
... handle input before going through next loop iteration ...
}
note that solutions which use the switch statement are just optimizations of the undesirable "too many if's" solution.

Related

Add asterisk when number is in range

this is my first time using this site so sorry if I do something wrong,
Here's an example output of the program I'm working on, basically what's supposed to happening
1-10 |**
11-20 |****
21-30 |***
31-40 |
41-50 |******
It goes on like that till the range of 91-100. This is my code so far, I've had a couple of different ideas so the code is incomplete in some parts but I really don't know which direction to go.
import java.util.Scanner;
public class HowMany
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
int range1 = 0;
int range2 = 0;
int range3 = 0;
int range4 = 0;
int range5 = 0;
int range6 = 0;
int range7 = 0;
int range8 = 0;
int range9 = 0;
int range10 = 0;
System.out.println("Enter integers between 1 and 100 (inclusive).");
System.out.println("Enter an integer out of the range to stop.");
//Assigning the user input a variable
int userNum = input.nextInt();
while(userNum >= 1 || userNum <= 100)
{
for (int i = 0; i < value; i++)
System.out.print("*");
if(userNum >= 1 && userNum <= 10)
}
}
}
Any help will be appreciated and if I haven't mentioned anything that I should specify let me know
Thanks
I don't think it would be beneficial for you if I just write you the program because this looks like exercise or homework, so let's work this out together. The program should run like this:
USER INPUT
If: 1..100 => PUT in the correct range and do 1)
Quit
The first observation is that
int userNum = input.nextInt();
needs to happen inside a loop, called the event loop. The structure is one big loop, that does the steps as stated above.
Now there is a better way to keep track of the ranges. Whenever you see yourself writing variables like var1, var2... you are better off with an array of values. The best would be to use an array of integers, where each index represents one range, something like this:
[0] 1-10
[1] 11-20
[2] 21-30 ...
and then you can just increment the correct index.
For instance, the user types in 34, you work out with the modulo operator where it goes and insert it.
Then I am sure you can find a smart way to print the final string. The best would be to create a separate print function for the array, something like:
printCounts(int[] count) { ... }
Hope those help, feel free to ask follow-up questions :)

The loop runs twice in a single run

This problem is from https://www.hackerrank.com/ and link to it is https://www.hackerrank.com/challenges/java-list/problem .
In the below code while loop is running twice as according to question we need to enter Q, Q times an operation to perform in the Array Declared. For this, i am running twice the loop so that I can get the desired result.
import java.util.*;
public class javaList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int i, x;
ArrayList L = new ArrayList(N);
for (i = 0; i < N; i++) {
L.add(sc.nextInt());
}
int Q = sc.nextInt();
i = 0;
// for normal running i have multiplied Q by 2 so that i can get the results
while (i < Q * 2) {
System.out.println("Loop: " + i);
String s = sc.nextLine();
int sz = L.size();
// code for checking insert
if (s.equals("Insert")) {
x = sc.nextInt();
int y = sc.nextInt();
//if the position i am looking exists then just replace
// i need to insert at index x of array L but array.size() gives one more than the last index
if ((sz - 1) >= x) {
L.add(x, y);
}
//if the position i am looking does not exist then create
else {
for (int j = sz; j <= x; j++) {
//add number to desired place
if (j == x)
L.add(y);
//in between the two endings of array and insertion adding default value 0
else
L.add(0);
}
}
//checking code for Delete
} else if (s.equals("Delete")) {
x = sc.nextInt();
//if the desired location exists then only replace
if ((sz - 1) >= x) {
L.remove(x);
}
}
i++;
}
for (i = 0; i < L.size(); i++) {
System.out.print(L.get(i) + " ");
}
}
}
I want to Know why the loop is running twice in a single run.
So, from discussion in the comments, you've stated that your question is:
if Q = 2 then it should ask operations Insert or Delete 4 times as of my code. But it asks only 2 times. Simply that is my problem
First, you may not fully understand your own program flow. Before the while loop, you need to enter three sets of values, a value for N, values for L, and a value for Q.
Once you enter your while loop, you will be prompted for a value for s (which it seems you intend to be either "Insert" or "Delete"). However, the first time around, it will get an empty string and s will be "\n". Why? Because for N, L, and Q, the user will enter values as follows:
[value] [ENTER]
The return key is itself a value. So, in the input buffer (assuming Q = 2), is "2\n". When your code runs to get s String s = sc.nextLine(); it will see the next line symbol and skip prompting user for input.
Because s is not "Insert" or "Delete", it will skip those the first time around. You will then be prompted to enter a value for "s" after the start next loop.
To help you realize what's going on, I suggest adding statements everywhere you ask users to enter a value, like System.out.println("Enter a value for Q:");
This will help you keep track of program flow.
Your code is waaay to complicated. Try this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
for (int i = 0, n = scanner.nextInt(); i < n; i++) {
list.add(scanner.nextInt());
}
for (int i = 0, n = scanner.nextInt(); i < n; i++) {
if (scanner.next().equals("Insert")) {
list.add(scanner.nextInt(), scanner.nextInt());
} else {
list.remove(scanner.nextInt());
}
}
String result = list.stream()
.map(String::valueOf)
.collect(Collectors.joining(" "));
System.out.println(result);
}

How to exclude -1 sentinel value when finding minimum element in an array, java

I'm trying to find the minimum element in an array of size 25 elements are read by user and should stop when the user enters -1
import java.util.*;
public class LabSheet4{
public static void main (String[] args){
Scanner read = new Scanner (System.in);
double scores[] = new double[25];
int minIndex=0, i =0, sentinel=0;
do{
scores[i] = read.nextDouble();
if(scores[i]==-1)
sentinel=-1;
i++;}while(sentinel!=-1);
for(int k=0;k<scores.length;k++)
if(scores[minIndex] > scores[k] && scores[minIndex]>0)
minIndex = k;
lowestScore = scores[minIndex];}}
How do I exclude -1?
One way would be to not put the value in the list until after you know it isn't the sentinel.
Another would be to not increment the counter when you find you have added the sentinel. Note that this means you need a slightly bigger array.
One way is not to store it in the first place but another fix would be to ignore it when running on the array like this.
for(int k=0;k<scores.length;k++)
if(scores[minIndex] > scores[k] && scores[minIndex]>0 && scores[k] !=1)
One common idiom for this class of problems, is to use a while loop with an assignment and test. Something like,
double scores[] = new double[25];
int i = 0;
double score;
while ((score = read.nextDouble()) != -1) {
scores[i] = score;
i++;
}
Then you could start at 0 and iterate from 1 to i (because 0 is your initial value and i is the count of elements). Like,
int minIndex = 0;
for (int k = 1; k < i; k++) {
if (scores[minIndex] > scores[k]) {
minIndex = k;
}
}
double lowestScore = scores[minIndex];
Instead of
if(scores[i]==-1)
sentinel=-1;
use
if (scores[i]==-1 && i > 0) {
sentinel=-1;
scores[i] = scores[minIndex];
}
so you replace -1 with (so far) the lowest value - which is OK, isn't it?.
Do not store -1 in scores at all.
That way you won't have to exclude it later.
Most importantly,
it's not a functional value like the other values you store,
but a symbol with a special technical meaning in the way you process input.
As such, it doesn't belong in the scores array.
Change your loop that reads the user input,
so as to not store -1.
Check the input before you store it,
and break out of the loop if it is -1:
while (true) {
double input = read.nextDouble();
if (input == -1) {
break;
}
scores[i++] = input;
}
Btw, what will happen if the user enters 26 values that are not -1?
The program will crash, because scores can only store 25 values.
So you need further some improvements to prevent that from happening.
For example you could use a for loop instead:
for (int i = 0; i < scores.length; i++) {
double input = read.nextDouble();
if (input == -1) {
break;
}
scores[i] = input;
}

Java reading in a string and converting numbers in strings into Integers types

I am trying to take numbers from a users string (if it has numbers) and convert those numbers to their numerical value. I have the following code which takes in user input.
Ex: java Convert "55s" will just output the number 55, which i will store for later usage
{
char Element = 0;
double Sum = 0;
boolean Check = false;
for(String s: args) // taking in user input for command line
{
for (int i = 0; i<s.length(); i++)
{
Check = true;
Element = s.charAt(i); // converting the string into chars
Sum = convert_to_numb (Element, Check);
Check = false;
}
}
The input is a string in which i separate into chars and send it to my conversion functions. The idea i have follows
public static double convert_to_numb (char elem, boolean check) //trying to convert chars to numbers
{
char iter = elem;
double number = 0;
int count = 0;
while (check == true)
{
number = number + (iter - 48) * Math.pow(10,count);
System.out.println(iter);
count ++;
}
return number;
}
Here I am feeding in the chars to see if they're numbers and convert the actual numbers into their integer value. To try to clarify i would like to perform the following task given an example input of "55" covert it to 5*10^1 + 5*10^0 = 55. I would appreciate any help. Thanks.
Alright, I think I might know what you're trying to accomplish, though as others have mentioned it is a little unclear.
To address the code you just posted, I don't think it'll behave the way you expect. For starters, the Boolean variable 'Check' accomplishes nothing at the moment. convert_to_numb is only called while Check is true, so it's redundant.
Additionally, the sum isn't being stored anywhere as you loop through the string. Every time you obtain a sum, it overwrites the previous one.
Your convert_to_numb method is even more troubling; it contains an infinite loop. Since Check is always set to 'true', you essentially have a while(true) loop that will never end.
I'm going to assume that your objective here is to parse whichever Strings are input into the program looking for groups of consecutive digits. Then you want to store these groups of digits as integers, perhaps in an array if you find multiple.
Something like this might do the trick.
{
ArrayList<Integer> discovered = new ArrayList<Integer>();
for (String s : args) {
// contains previous consecutive digits (if any)
ArrayList<Integer> digits = new ArrayList<Integer>();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
// add digit to digit array
if (c.isDigit()) {
digits.add(c.getNumericValue())
}
// not a digit, so we clear the digit array
else {
// combine the array to form an integer
if (! digits.isEmpty()) {
int sum = 0;
int counter = 0;
for (Integer i : digits) {
sum += i * Math.pow(10, counter);
counter++;
}
discovered.add(sum);
digits.clear();
}
}
}
}
}
Note the use of ArrayLists and the Integer and Character wrapper classes. These all provide functionality that helps deal with edge-cases. For example, I'm not sure that (iter - 48) part would have worked in all cases.
Something like this:
public static void main(String[] args) {
String string = "55s";
String[] piece = string.split("[\\D]+");
for (int j = 0; j < piece.length; j++) {
if(piece[j].trim().length() > 0) {
System.out.println(piece[j]);
}
}
}
It will split your initial string, the rest you should do yourself.

Java Double Array

I'm having trouble setting up and placing values into an array using a text file containing the floating point numbers 2.1 and 4.3 each number is separated by a space - below is the error I'm getting:
Exception in thread "main" java.util.NoSuchElementException
import java.util.*;
import java.io.*;
public class DoubleArray {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new FileReader("mytestnumbers.txt"));
double [] nums = new double[2];
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++;
nums[index] = in.nextDouble();
}
}
}
Thanks, I'm sure this isn't a hard question to answer... I appreciate your time.
You should always use hasNext*() method before calling next*() method
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[1] = in.nextDouble();
}
}
but I think you are not doing the right, I'd rather
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[counter] = in.nextDouble();
}
}
NoSuchElementException is thrown by nextDouble method #see javadoc
I would suggest printing the value of index out immediately before you use it; you should spot the problem pretty quickly.
It would appear you're not getting good values from your file.
Oli is also correct that you have a problem with your index, but I would try this to verify you're getting doubles from your file:
String s = in.next();
System.out.println("Got token '" + s + "'"); // is this a double??
double d = Double.parseDouble(s);
EDIT: I take this partly back...
You simply don't have tokens to get. Here's what next double would have given you for exceptions:
InputMismatchException - if the next token does not match the Float
regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
I did not understand what you are trying to do in your loop ?
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++; <--------
nums[index] = in.nextDouble();
}
You are declaring index = 0 then incrementing it to 1 and then using it.
Why are you not writing int index = 1; directly ?
Because it is getting declared to be zero each time loop is run and then changes value to 1.
Either you should declare it out side the loop.
You should initialize index outside of your for loop.
int index = 0;
for (int counter=0; counter < 2; counter++)
{
index++;
nums[index] = in.nextDouble();
}
Your index was getting set to zero at the beginning of each iteration of your for loop.
EDIT:
You also need to check to make sure you still have input.
int index = 0;
for (int counter=0; counter < 2; counter++)
{
if(!in.hasNextDouble())
break;
index++;
nums[index] = in.nextDouble();
}
Every time the cycle does an iteration, it's declaring the variable index and then you increase index with index++. Instead of using index, use counter, like this: num [counter] = in.nextDouble().
Check your mytestnumbers.txt file and ensure that the data that you are trying to scan is in the correct format. The exception that you are getting implies it is not.
Keep in mind that in.nextDouble() will be searching for double numbers separated by white space. In other words, "4.63.7" is not equal to "4.6 3.7" — the space is required. (I do not remember off the top of my head, but I believe that nextDouble() will only search for numbers containing a decimal point, so I do not believe that "4" is equal to "4.0". If you are seeking decimal numbers with this method, then you should have decimal numbers in your file.)

Categories

Resources