so I'm creating a program that will to determine a final semester class grade given assignment and test grades and the percentages that they count for in that grade. The grade and percentage information for a single student will be given on a single line. Soooo, I just one question:
q1 = input.nextInt();
q1p = input.nextDouble();
q2 = input.nextInt();
q2p = input.nextDouble();
q3 = input.nextInt();
q3p = input.nextDouble();
l1 = input.nextInt();
l1p = input.nextDouble();
l2 = input.nextInt();
l2p = input.nextDouble();
l3 = input.nextInt();
is there a better way to simplify this mess of input of int & double??
From what I can see from your input variable, it looks like you're working with the Scanner API, am I right ? If so, well there's something pretty nice that you could do using a simple look and the condition has next from the Scanner to verify that there's input to read. Finally, to detect if input is a double or an int, we're gonna make a easy check to make sure !
Collection<Integer> integers= new ArrayList<>();
Collection<Double> doubles = new ArrayList<>();
while(input.hasNext())
{
if (input.hasNextInt()) {
integers.add(input.nextInt());
}else if(input.hasNextDouble()) {
doubles.add(input.nextDouble());
}else
input.next(); // will simply move to next value in the line
}
This way not only you don't have to check everytime like you did before nextInt or NextDouble with a static user input, you won't have to worry. And if the input isn't a double or an int, well, the lists will remain empty !
UPDATE
Change the use of List for the Collections in order to cause less troubles during run time ! The solution should work out great for you at the moment. I also added a clause in the if structure in order to make the loop complete when hasNext == false
You can use two arrays and loop over them:
int numberOfInputs = XXX;
int[] ints = new int[numberOfInputs];
double[] doubles = new double[numberOfInputs];
for (int i = 0; i < numberOfInputs; i++)
{
ints[i] = input.nextInt();
doubles[i] = input.nextDouble();
}
If you need it more flexible and have no problems with (un)boxing you could use a Colletion:
Collection<Integer> ints = new ArrayList<>();
Collection<Double> doubles = new ArrayList<>();
while (moreInput)
{
ints.add(input.nextInt());
doubles.add(input.nextDouble());
}
moreInput is an arbitrary condition that you need to adjust to your needs.
You might add conditions in the loops if there are for example 2 ints and 1 double.
Related
I am new to learning about parallel arrays and want to know how to effectively print content/elements using parallel array only, I tried but couldn't get it to work and function the way I want.
The task is: The program inputs an integer from the user representing how many peoples’ information will be entered. Then, the program inputs the information one person at a time (name first, then age), storing this information in two related arrays.
Next, the program inputs an integer representing the person on the list whose information should be displayed (to get information for the first person, the user would enter ‘1’). The program makes a statement about the person’s name and age.
Although I got the name and age to work until the integer the user inputs, but after that I am not sure how to do
Sample input:
4
Vince
5
Alexina
8
Ahmed
4
Jorge
2
2 // I am confused about this part, how would I make it so that it prints the desired name,
//for example with this input, it should print:
Sample output:
Alexina is 8 years old
My code:
import java.util.Scanner;
class Example {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < num.length; x++){
String[] name = {keyboard.next()};
int[] age = {keyboard.nextInt()};
}
int num2 = keyboard.nextInt();
System.out.println(); // what would I say here?
}
}
You need to rewrite your code so your arrays aren't being assigned within the loop. You want to add values to the arrays, not reset them each time, and you want to be able to access them afterwards. Below is a modified version of your code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
keyboard.nextLine(); //you also need to consume the newline character(s)
String[] name = new String[num]; //declare the arrays outside the loop
int[] age = new int[num];
for (int x = 0; x < num; x++){
name[x] = keyboard.nextLine(); //add a value instead of resetting the array
age[x] = keyboard.nextInt();
keyboard.nextLine(); //again, consume the newline character(s) every time you call nextInt()
}
int num2 = keyboard.nextInt() - 1; //subtract one (array indices start at 0)
System.out.println(name[num2] + " is " + age[num2] + " years old"); //construct your string with your now-visible arrays
}
As I think you have to think about the local and global variable usage in java.In brief,
Local variables can only use within the method or block, Local variable is available only to method or block in which it is declared.
For example:
{
int y[]=new Int[4];
}
this y array can be accessed within the block only.
Global Variable has to be declared anywhere in the class body but not inside any method or block. If a variable is declared as global, it can be used anywhere in the class.
In your code you try to create arrays and use them out of the For loop. But your arrays are valid only inside the For loop. After every loop runs all info is lost.there will be new array creation for every iteration of For loop.
therefore, In order to access and save the information you have to declare your arrays before the For loop and access and store data using iteration number as the index. finally, to print the data you gathered, you have to scan new input as integer variable.then you can access your arrays as you wanted.
//For example
int [] age=new int[4]; //global -Can access inside or outside the For loop
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < 4; x++){
age[x] = keyboard.nextInt(); //Local
}
int num2 = keyboard.nextInt();
System.out.println(age[num2]); // Here you have to access global arrays using num2 num2
}
}
My teacher wants me to be able to ask this question an infinite number of times until the user decides to terminate it themselves. This works for the most part however, If I input a number too big I get an error because its a int data type. I have tried longs and doubles to but for some reason I get answers like infinity or the negative of the numbers. How do I fix this so I can put in as long of a number that I want and still get the positive integer reversal? Thank You so Much. Please keep it simple. This is literally my 5th computer class in my life.
import java.util.Scanner;
public class reverseInt3
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int number;
int reverse = 0;
int number2;
int reverse2 = 0;
char repeat;
System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();
while( number != 0 )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
System.out.println("Reverse of entered number is "+reverse);
System.out.println("Do you want to repeat the process using different numbers? Y or N");
repeat = keyboard.nextLine().charAt(0);
while( repeat == 'Y' || repeat == 'y')
{
System.out.println("Please enter your new set of numbers");
number2 = keyboard.nextInt();
keyboard.nextLine();
while( number2 != 0 )
{
reverse2 = reverse2 * 10;
reverse2 = reverse2 + number2%10;
number2 = number2/10;
}
System.out.println("The reverse of entered number is "+reverse2);
System.out.println("Do you want to repeat the process using different numbers? Y or N");
repeat = keyboard.nextLine().charAt(0);
}
}
}
First let's talk about your problem:
If the user input goes beyond the bound of int, long or double your program provides a negative reverse.
That's because when you try to store a very big number in smaller capacity variable, an overflow happens and after that your stored number is not valid and if you try to print it you will get a negative number instead which is not the exact negative for the user input.
If you want to overcome this, one way is to store the user input in a String variable. Then you can check if the input (which is stored in a String type variable) is really an integer or not, and if it was, you can reverse it.
I don't think this is actually what your teacher want you to do. Because the algorithm of reversing an integer (you implemented) can not be used to reverse such a big integer stored in a String variable. So I think your code is good and get it easy because probably your teacher don't expect you to maintain very big integers now. If you so worry about some bigger integers you can use long instead of int but as you know it has its own limitation about 18 digits approximately and it should not be bigger than Long.MAX_VALUE.
Your code is good for the start and I'm going to express some advice in order to provide a better and cleaner code:
It's obvious that you've repeated these part of codes:
System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();
and
while( number != 0 )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
and
System.out.println("Reverse of entered number is "+reverse);
If you studied methods so far, you may want to define these two first blocks in two different methods. One is responsible for getting input from user and the other one is responsible for getting an int as input and return the reversed int (If you used long for user input, this method's input and output should be of type long).
Another tip is why repeat those blocks? Why have two number and number2 variables and also reverse and reverse2?
Isn't it better to omit them and write your while for the repetition of the process in the first time too? Start by initializing the char repeat = 'Y'; and omit the first time you manually get the job done outside of the while( repeat == 'Y' || repeat == 'y') loop.
Hope this helps.
I am new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}
Forgive me if this has already been asked, but I am trying to fill an array of user defined size, but I want to make sure any extra input is either dumped or triggers an error to reprompt for input. My assignment requires that all input for an array is done on one line, with spaces separating individual values. The program works fine, and seeing how we are still in the beginning of the class I don't think that we are expected to know how to filter the quantity of inputs on a single line, but it is something that still bugs me.
I have searched for some time now for a solution, but everything thing I find is not quite what I am looking for. I thought doing a while(scannerVariable != "\n") would work, but once I thought about it more I realized that wouldn't do anything for my problem since the new line character is only being encountered once per array regardless of the number of inputs. The snippet with the problem is below:
public static double[] getOperand(String prompt, int size)
{
System.out.print(prompt);
double array[];
array = new double[size];
for(int count = 0; count < size; count++)
{
array[count] = input.nextDouble();
}
return array;
}
All I need is some way of validating the number of inputs or dumping/ignoring extra input, so that there is no trash in the buffer to skip input that follows. The only way I can think of is counting the number of spaces and comparing that against the size of the array -1. I don't think that would be reliable though, and I'm not sure how to extract a whitespace character for the count unless I were to have all the input go into a string and parse it. I can post more code or provide more details if needed. As always, thanks for any help!
This can help you. Function that allows the entry of numbers on a line separated by spaces. Valid numbers are stored in a list of type Double.
public static void entersDouble () {
Scanner input = new Scanner(System.in);
String s;
ArrayList<Double> numbers= new ArrayList<>();
System.out.print("Please enter numbers: ");
s=input.nextLine();
String [] strnum = s.split("\\s+");
int j=0;
while(j<strnum.length){
try {
numbers.add(Double.parseDouble(strnum[j++]));
}
catch(Exception exception) {
}
}
for (Double n : numbers)
System.out.println(n);
}
It seems to me that rather than trying to work out the number of inputs up front you would be better off trying to read them one by one and then taking appropriate action if it's too long or too short.
For example
public static double[] getOperands(String prompt, int size) {
double[] operands = new operands[size];
while (true) {
System.out.println(prompt);
Scanner scanner = new Scanner(System.in);+
int operandCount = 0;
while (scanner.hasNextDouble()) {
double val = scanner.nextDouble();
if (operandCount < size)
operands[operandCount++] = val;
}
if (operandCount == size)
return operands;
else
System.out.println("Enter " + size + " decimals separated by spaces.");
}
}
The input of the program contains n amount of doubles.
I want each double stored as: a(n), where n = n++
like this:
input 6,57 4,56 1,23
should be stored as:
a(0) = 6,57
a(1) = 4,56
a(2) = 1,23
etc.
This is what i've tried to do:
double a;
int n = 0;
scanner = new Scanner(System.in);
a(n) = scanner.nextDouble();
while (scanner.hasNextDouble()) {
a(n) = scanner.nextDouble();
n++;
break;
}
This does not work out,
any ideas?
Thanks in advance.
You don't know about size inadvance ,So I suggest to use List<Double> instead of array.
You have number in local format (seperated by ,) so use NumberFormat class to get the java format.
Numbers are separated with space and are stored in a line in your input,so use next() method.
Try this code.
List<Double> a = new ArrayList<Double>();
scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String number = scanner.next();
NumberFormat numberFormat = NumberFormat.getInstance();
a.add(numberFormat.parse(number).doubleValue());
}
You will need to use an array. Arrays are fixed size so you must know the number of elements in advance.
Create the array with double[] a=new double[size] where size is the array size you want.
You can now set the array's values with a[n]=scanner.nextDouble();. Remember that n will go from 0 to size-1. You can read out values this way as well, for example `System.out.println(n[2]);