I really need help with my program. I'm trying to make a cumulative grade calculator in java, using arrays and dialog boxes. For some reason, my arrays won't print out the input made by the user which is throwing off my calculations. How can I give it the correct value?
{
// First array - Length
int[] arNumber = null;
int number;
String str;
// Second array - Elements
int numbers;
int[] arNumbers = null;
int total = 0;
int gradeSum = 0;
String str2;
String message = "How many grades will you input in this class?";
str = JOptionPane.showInputDialog(message);
number = Integer.parseInt(str);
arNumber = new int[number];
for(int index = 0; index < arNumber.length; index++)
{
String message2 = "Insert your grade";
str2 = JOptionPane.showInputDialog(message2);
numbers = Integer.parseInt(str2);
arNumbers = new int[numbers];
}
for (int element : arNumbers)
{
// Print array onto console
System.out.println(element);
// Add all elements
gradeSum += element;
// Print grade onto console
System.out.println(gradeSum);
}
total = gradeSum / arNumber.length;
return total;
}```
It looks like you don't need to use two arrays. The line with arNumbers = new int[numbers]; means that arNumbers is getting reinitialized as a new array for every iteration of that loop. Try using arNumber[index] = numbers; to assign the user-entered value into the arNumber array and do away with arNumbers. Then loop over arNumber in the second loop.
Also note that total is declared as an int which will truncate your floating point value, which I'm guessing you don't want. Good luck!
Related
My question is what they do " smallest" variable and the if statement. I know what the program do but it cost me to understand well the flow execution of this part .
import java.util.Scanner;
import java.util.ArrayList;
public class IndexOfSmallest {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while(true){
int numbers = Integer.valueOf(reader.nextLine());
if(numbers == 9999){
break;
}
list.add(numbers);
}
int index;
int smallest = list.get(0);
for (int i = 0; i < list.size();i++){
int number = list.get(i);
if ( smallest > number){
smallest = number;
}
}
System.out.println(smallest);
}
}
This is a rather simple console application. You should try to read your code line by line when you are starting to learn a new language.
This way you can show some effort and ask more clear and concise questions. Here is an example to go about reading your code line by line. If you don't know what some function is doing, look up that function.
Just take your time, you'll get used to the syntax and it will get easier every time.
Scanner reader = new Scanner(System.in); // Create scanner taking console inputs
ArrayList<Integer> list = new ArrayList<>(); // Create list
while(true){ // Endlessly loop
// Keep reading input from console until user inputs 9999, then break
int number = Integer.valueOf(reader.nextLine());
if(number == 9999){
break;
}
list.add(number); // Add number to list
}
/* int index; // This is worthless, not used again */
int smallest = list.get(0); // Variable to store smallest number
for (int i = 0; i < list.size();i++){ // Increase i until list size is reached
int number = list.get(i); // Get number for position i in list
if ( smallest > number){ // Compare
smallest = number; // Set new smallest number
}
}
System.out.println(smallest); // Print
My array is filled in the beginning with a string. Then the user can enter a new string. I want my array to shift to the right, like {a,x,x,x} should move the a to the right {x,a,x,x} so new entries can move up. When I run my code it puts the entered string in the first position of the array, but in the next step it doesn't move the entered string, but prints out an array only filled with the predefined string. Why doesn't it contain my entered string?
public static void main(String args[]) {
int i;
String n = new String("n");
Scanner sc = new Scanner(System.in);
String a;
String affe [] = new String [5];
Arrays.fill(affe, n);
a = sc.next();
affe[0] = a;
System.out.println(Arrays.toString(affe));
for(i = 0; i<affe.length-1; i++){
affe[i] = affe[i+1];
}
System.out.println(Arrays.toString(affe));
}
Try
Collections.rotate(Arrays.asList(affe), 1);
You're copying the wrong way around.
Change this line:
affe[i] = affe[i+1];
to
affe[i+1] = affe[i];
But you also need to change the order of the loop to go from back to front. Otherwise, each subsequent iteration brings the one value from the start forward to the end. So change the loop to:
for (int i = affe.length - 2; i >= 0; i--) {
affe[i+1] = affe[i];
}
I am working on a program and I will be asking the user to input a string full of characters with no spaces. I will then be splitting this string up into parts of three characters each, and I would like to populate an array with these new strings of three characters. So basically what I am asking is how would I create a method that takes an input string, splits it up into separate parts of three, then populates an array with it.
while (i <= DNAstrand.length()-3) {
DNAstrand.substring(i,i+=3));
}
This code will split the string up into parts of three, but how do I assign those values to an array in a method?
Any help is appreciated thanks!
Loop through and add all the inputs to an array.
String in = "Some input";
//in.length()/3 is automatically floored
String[] out = new String[in.length()/3];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
This will ignore the end of the String if it's length isn't a multiple of 3. The end can be found with:
String remainder = in.substring(i, in.length());
Finally, if you want the remainder to be part of the array:
String in = "Some input";
//This is the same as ceiling in.length()/3
String[] out = new String[(in.length()-1)/3 + 1];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
out[out.length-1] = in.substring(i, in.length());
Try this:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> arr = new ArrayList<String>();
String temp = "";
int count = 0;
for(int i = 0; i < text.length(); i++)
{
if(count < 3)
{
temp += String.valueOf(text.charAt(i));
count++;
if(count == 3)
{
arr.add(temp);
temp = "";
count = 0;
}
}
}
if(temp.length() < 3)arr.add(temp);//in case the string is not evenly divided by 3
return arr;
}
You can call this method like this:
ArrayList<Strings> arrList = splitText(and the string you want to split);
i have an integer values as:
1299129912
i want to store it as
12
12
12
in the int v1,v2,v3;
i.e.,when ever 9909 occurs we need to separate the values individually. Is it possible in java. If so please anyone help me.
here is the code I'm trying
int l = 1299129912;
Pattern p = Pattern.compile("99");
Matcher m1 = p.matcher(l);
if (m1.matches()) {
System.out.println("\n");
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method matcher(CharSequence) in the type Pattern is not applicable for the arguments (int)
I suppose you already have the value as a String since 1234990912349909 is more that Integer.MAX_VALUE. Then you can split the string into String[] and do whatever you want with the separate values. E.g. call parseInt on each element.
String[] values = myIntString.split("9909");
for (String value: values) {
int v = Integer.parseInt(value);
}
Yes, it is very possible in java. Just convert the integer to a string and replace the 9909 with a space.
Example:
String s="1234990912349909";
s=s.replaceAll("9909","");
int a=Integer.parseInt(s);
System.out.println(a);
//output would be 12341234
If you know you are always going to have 3 integers named v1, v2, and v3 the following would work:
String[] numbers = l.toString().split("99");
int v1 = Integer.parseInt(numbers[0]);
int v2 = Integer.parseInt(numbers[0]);
int v3 = Integer.parseInt(numbers[0]);
However if you don't know in advance then it might be better to do it like this:
String[] numbers = l.toString().split("99");
int[] v = new int[numbers.length];
for (int i = 0; i < numbers.length; i++)
v[i] = Integer.parseInt(numbers[i]);
I found out this is the easiest way to show you how you can resolve your issue:
I included clear comments on every important step. Please check this:
int num = 1239012390;
// Convert int into a string
String str = String.valueOf(num);
// What separates the values
String toBremoved = "90";
String str1 = "";
// Declare a String array to store the final results
String[] finalStrings = new String[2];
// i will be used as an index
int i = 0;
do {
// Finds and separates the first value into another string
finalStrings[i] = str.substring(0, str.indexOf(toBremoved));
// removes the first number from the original string
str = str.replaceFirst(finalStrings[i], "");
// Remove the next separating value
str = str.replaceFirst(str.substring(str.indexOf(toBremoved), str.indexOf(toBremoved) + toBremoved.length()), "");
// increments the index
i++;
} while (str.indexOf(toBremoved) > 0); // keeps going for a new iteration if there is still a separating string on the original string
// Printing the array of strings - just for testing
System.out.println("String Array:");
for (String finalString : finalStrings) {
System.out.println(finalString);
}
// If you want to convert the values into ints you can do a standard for loop like this
// Lets store the results into an int array
int [] intResults = new int [finalStrings.length];
for (int j = 0; j < intResults.length; j++) {
intResults[j] = Integer.valueOf(finalStrings[j]);
}
// empty line to separate results
System.out.println();
// Printing the array of ints
System.out.println("int Array:");
for (int intResult : intResults) {
System.out.println(intResult);
}
Or in a simplified and more accurate way:
(you can use the example above if you need to understand how it can be done the long way)
int num = 1239012390;
String [] numbers = String.valueOf(num).split("90");
int num1 = Integer.parseInt(numbers[0]);
int num2 = Integer.parseInt(numbers[1]);
System.out.println("1st -> " + num1);
System.out.println("2nd -> " + num2);
I am fairly new to Java and am struggling with this concept. As I have said I am trying to make a comparison between 2 sets of integer values, one set I have retrieved from the website using HTML parsing and stored in an array (Integer [] numbers = new Integer[split.length]).
The other set of values I have retrieved from user input and have stored in the array userNumbers (int userNumbers = new int [SIZE]). I attempted to use the if condition to make the comparison i.e. if (userNumber[count] == number [0]).
However I am getting errors and the IDE is not allowing me to enter the number array part of the comparison. Can anyone help me to understand why this is or instruct me as to what I may be doing wrong? Here is the code in full.
Help is very much appreciated in advance.
public class lotteryNumbers
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
//link to the intended web site
try {
Document doc = Jsoup.connect("http://www.national-lottery.co.uk/player/p/drawHistory.do").get();
Elements elements = doc.getElementsByClass("drawhistory");
Element table = elements.first();
Element tbody = table.getElementsByTag("tbody").first();
Element firstLottoRow = tbody.getElementsByClass("lottorow").first();
Element dateElement = firstLottoRow.child(0);
System.out.println(dateElement.text());
Element gameElement = firstLottoRow.child(1);
System.out.println(gameElement.text());
Element noElement = firstLottoRow.child(2);
System.out.println(noElement.text());
String [] split = noElement.text().split(" - ");
// set up an array to store numbers from the latest draw on the lottery web page
Integer [] numbers = new Integer [split.length];
int i = 0;
for (String strNo : split) {
numbers [i] = Integer.valueOf(strNo);
i++;
}
for (Integer no : numbers) {
System.out.println(no);
}
Element bonusElement = firstLottoRow.child(3);
Integer bonusBall = Integer.valueOf(bonusElement.text());
System.out.println("Bonus ball: " + bonusBall);
//Elements elementsHtml = doc.getElementsByTag("main-article-content");
} catch (IOException e) {
e.printStackTrace();
}
final int SIZE = 7;
//array to store user numbers
int [] userNumbers = new int[SIZE];
//array to check if user number is present with web numbers
boolean [] present = new boolean[7];
int counter = 0;
while (counter<SIZE)
{
System.out.println("enter your numbers");
userNumbers[counter]=keyboard.nextInt();
counter++;
}
for (int count: userNumbers)
System.out.println(count);
if (userNumbers[0] == )
The numbers local variable is declared in the try{...} block. Thus it is not accessible outside it.
If you declare it before the try{ line it will work:
Integer[] numbers;
try {
...
// set numbers here
...
} catch (IOException e) {
...
}
// can use numbers here
If it is the only value you need from the HTML-parsing code you may even refactor the try/catch structure to a method returning the data for numbers.
And by the way, I advise you not to try int == Integer, prefer int == int. It is usually clearer and you won't have to guess if the int will be boxed or the Integer unboxed.